context.Context carries deadlines, cancellation signals, and other request-scoped values across API boundaries and goroutines. This example demonstrates using context with HTTP servers to control cancellation.
Context in HTTP Servers
HTTP servers are useful for demonstrating the usage ofcontext.Context for controlling cancellation. The net/http machinery creates a context for each request automatically.
How Context Cancellation Works
Monitor Done Channel
Use the
ctx.Done() channel in a select statement to detect when the request is cancelled.Handle Cancellation
When
ctx.Done() closes, call ctx.Err() to get the reason (e.g., timeout, client disconnect).The Select Pattern
Theselect statement is key to responding to context cancellation:
This pattern allows your server to gracefully handle client disconnections and timeouts, preventing wasted resources on abandoned requests.
When Context Gets Cancelled
Client Disconnect
Client Disconnect
When a client closes the connection (e.g., hitting Ctrl+C on a curl request), the context is automatically cancelled.
Request Timeout
Request Timeout
If the server or client has configured a request timeout, the context will be cancelled when the deadline is reached.
Explicit Cancellation
Explicit Cancellation
You can create contexts with explicit cancellation functions using
context.WithCancel() for custom cancellation logic.Running the Example
Best Practices
Always Check Context
Long-running operations should regularly check
ctx.Done() to respect cancellation.Pass Context Down
Pass the context to any functions or goroutines that do work on behalf of the request.
Don't Store Contexts
Contexts are request-scoped. Never store them in structs or use them beyond the request lifecycle.
Use Context Values Sparingly
Only use context values for request-scoped data like authentication tokens, not for passing optional parameters.
Next Steps
HTTP Server
Learn more about building HTTP servers
HTTP Client
Make HTTP requests with context support