liveBook · Manning

Context

As explained in Go by Example

context.Context is a Go standard-library interface that carries cancellation signals, deadlines, and request-scoped values across call boundaries.

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.
A diagram of a parent canceling

AI-generated content may be incorrect.

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

How Go by Example covers it

How deep it goes
Explains tree semantics, Done-based handling, timeout cleanup, HTTP propagation, and value middleware; defers full cancellation of every pipeline stage as an exercise.
Examples
Demonstrates a cancellable request pipeline, derived iterator Context, Ctrl+C-aware CLI, trace-ID middleware, and HTTP client test.
What it assumes
Assumes Go concurrency and HTTP request use while introducing Context roots, derivation, cancellation signals, and value retrieval.
What you can do after
Apply it via the context package to stop concurrent work gracefully, propagate request cancellation, and carry informational trace IDs.
How it connects
Connects Context with goroutines, channels, select, HTTP requests, middleware, slog.Handler, iterators, and testing.T.Context.

Also explained in

Compare how 7 books explain context →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.