liveBook · Manning

Context

As explained in Go in Action, Second Edition

A Go context is a request-scoped value carrying cancellation, deadlines, and other propagation metadata across call boundaries.

Context carries cancellation, deadlines, and request-scoped metadata across call boundaries. In a concurrent HTTP service, it gives downstream goroutines an escape switch when a client disconnects or an operation exceeds its deadline, preventing work from continuing without a reader. section 1.4.3 section 9.3

Use context to:

  • Set an overall deadline, such as 60 seconds for all downstream operations. section 9.3
  • Pass cancellation through database, HTTP, and other request-scoped operations. section 9.3
  • Derive a context that cancels related work when one concurrent operation fails. section 9.3
  • Keep contexts temporary and pass them as values rather than embedding them in structs. section 9.3

Bounded, coordinated feed fetching

Create a timeout at the request boundary, pass the derived context into each fetch, and defer cancellation for cleanup: `ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second); defer cancel(); fetchFeeds(ctx, urls)`. Inside `fetchFeeds`, derive `ectx` with `errgroup.WithContext(ctx)` and call `fetchFeed(ectx, url)`. A failed fetch can then cancel the remaining feed requests, while `ParseURLWithContext` observes the deadline and cancellation. section 9.3

Figure 1.4 The life cycle of a single HTTP request

Trace one HTTP request from its handler through child goroutines, database work, and downstream APIs as cancellation propagates. section 1.4.3

How Go in Action, Second Edition covers it

How deep it goes
Demonstrates timeout creation, deferred cancellation, propagation, and errgroup derivation, without detailing Context internals.
Examples
Uses a 60-second request timeout, RSS feed fetching, ParseURLWithContext, and errgroup cancellation across concurrent fetches.
What it assumes
Assumes Go concurrency concepts and introduces context within request handling and concurrent feed fetching.
What you can do after
Apply context via the standard package to bound operations and cancel related concurrent work.
How it connects
Connects context with goroutines, channels, HTTP clients, database operations, errgroup, cancellation, and deadlines.

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 in Action, Second Edition. The section links point to the parts of the book it draws on.