context package defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
The Context Interface
Creating Contexts
Background and TODO
WithCancel
Create a context that can be manually cancelled.WithTimeout and WithDeadline
Create contexts that cancel automatically after a duration or at a specific time.WithValue
Carry request-scoped data through the call chain.Practical Examples
HTTP Request with Timeout
Database Query with Context
Worker Pool with Cancellation
Chained Context Operations
WithCancelCause (Go 1.20+)
Provide a reason for cancellation.Best Practices
1. Pass Context as First Parameter
2. Don’t Store Context in Structs
3. Always Call Cancel Functions
4. Don’t Pass nil Context
5. Use Typed Keys for Context Values
Context Errors
When to Use Context
Use Context for:- Request timeouts and deadlines
- Cancellation signals across goroutines
- Request-scoped values (user ID, trace ID, etc.)
- Propagating cancellation through call chains
- Optional function parameters
- Storing application state
- Passing values that should be function arguments
- Long-lived background operations that shouldn’t be cancelled