Context Package in Go – Timeouts, Cancellation, and Best Practices
What is the context Package?
The context package carries deadlines, cancellation signals, and request-scoped values across API boundaries and between goroutines.
Setting a Timeout
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
select {
case <-time.After(5 * time.Second):
fmt.Println("Work finished")
case <-ctx.Done():
fmt.Println("Timeout:", ctx.Err())
}
Manual Cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(1 * time.Second)
cancel() // cancels the context
}()
<-ctx.Done()
fmt.Println("Cancelled:", ctx.Err())
Best Practices
- Always call
cancel()(usually viadefer) to release resources, even if the operation completes normally. - Pass
context.Contextas the first parameter of functions that perform I/O or long-running work. - Avoid storing large amounts of data in a context — it's meant for small, request-scoped values.
PreviousWorking with Databases in Go – GORM and SQL Connections
Next Deploying Go Applications – Dockerize and Host on AWS/GCP
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)