What is Context?
The context package provides a way to carry deadlines, cancellation signals, and request-scoped values across API boundaries and goroutines. Every Go server and CLI should use context for proper request lifecycle management.
import "context"
// WithTimeout: cancel after 5 seconds
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // Always defer cancel to free resources
// WithCancel: manual cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(2 * time.Second)
cancel() // Cancel after 2 seconds
}()
// Check if context is done
select {
case <-ctx.Done():
fmt.Println("Cancelled:", ctx.Err())
case result := <-doWork(ctx):
fmt.Println("Result:", result)
}
Context Rules
1. Context should be the first parameter of every function: func DoSomething(ctx context.Context, ...). 2. Never store context in a struct. 3. Always call cancel() when done. 4. Pass context down, never up.
Key Takeaway: Use
context.WithTimeout for HTTP clients and database queries. Use context.WithCancel for long-running goroutines. Always pass context as the first function parameter.Practice Exercises
Medium Build a Mini Project
Combine concepts from this tutorial to build a small utility or tool.
Medium Debug Challenge
Introduce a bug in one of the code examples and practice finding and fixing it.
Hard Refactoring Exercise
Rewrite one example using a different approach and compare the tradeoffs.