context.Context carries cancellation signals, deadlines, and request-scoped values across API and goroutine boundaries. It lets long-running work stop when a request is canceled or a timeout expires, but cancellation is cooperative: each consumer must listen and return. section 7.2.1 section 7.8
Contexts form an immutable parent-child tree. Start with context.Background, then derive children with context.WithCancel or context.WithTimeout. Canceling a parent cancels its descendants; a child cannot cancel its parent or outlive its deadline. Always call a returned cancel function to release resources, including timer-tracking goroutines. section 7.2.2
Figure 7.3 Cancellation signals propagate through the hierarchy. Canceling the parent cancels both the parent and its children. The cross-out indicates the cancellation.
The hierarchy makes cancellation direction visible: signals flow from parent to children, never upward. section 7.2.2
Use Context deliberately at call boundaries:
- Accept it as the first parameter and pass it through to work that should stop together; avoid storing it in a struct. section 7.2.3
- Wait on ctx.Done() alongside normal channel operations with select. On cancellation, close or stop the stage so downstream stages can finish. section 7.2.3 section 7.7
- Derive an internal child Context when an iterator or operation may end before its caller cancels, then defer its cancellation. section 7.2.4
- Attach Context to HTTP requests by cloning them, allowing in-flight requests to observe cancellation. section 7.2.3
Graceful Ctrl+C shutdown
A CLI can create a signal.NotifyContext from context.Background and pass it into its request pipeline. The first Ctrl+C cancels the Context rather than immediately terminating the process, so the pipeline stops and the CLI can print results accumulated so far. section 7.2.5
Context values suit peripheral request metadata such as trace IDs. Middleware can add a trace ID to a cloned request Context, and downstream handlers and loggers can retrieve it. Use an unexported key type to prevent collisions; because Value returns any and makes data flow implicit, do not use Context values to drive program logic. section 9.5 section 9.5.1 section 9.5.2
Trace-ID middleware
A handler checks Request.Context for an existing trace ID. If absent, it generates one, derives a value-bearing Context, clones the request with it, and calls the next handler. Every downstream component receiving that request can correlate its logs with the same ID. section 9.5.2
Context also fits tests: pass testing.T.Context to work that should end with the test. This keeps cancellation ownership aligned with the test lifetime while exercising concurrent HTTP work. section 7.6.2






