Go Snippet

Context-Driven Cancellation

Difficulty: Medium

`context.Context` is Go's standard mechanism for cancelling long-running operations: a deadline, a parent-child cancellation tree, and a request-scoped value bag. This snippet shows `context.WithTimeout` to bound a function's runtime, the `select { case <-ctx.Done(): ... }` pattern in workers, and how to attach a request-id value. Pass `ctx` as the first argument to every function that does I/O or has a chance of blocking.

Code Snippets
/

Context-Driven Cancellation

Context-Driven Cancellation

`context.Context` is Go's standard mechanism for cancelling long-running operations: a deadline, a parent-child cancellation tree, and a request-scoped value bag. This snippet shows `context.WithTimeout` to bound a function's runtime, the `select { case <-ctx.Done(): ... }` pattern in workers, and how to attach a request-id value. Pass `ctx` as the first argument to every function that does I/O or has a chance of blocking.

Go
Medium
3 snippets
go-context
go-concurrency-patterns
go-channels
concurrency

158 views

3

context.WithTimeout(parent, d) returns a derived context that auto-cancels after d, plus a cancel function you should defer even if the timeout fires first (it releases internal resources). The callee blocks in a select waiting for either work to complete or ctx.Done() to close, returning ctx.Err() (context.DeadlineExceeded or context.Canceled) on timeout. This pattern is what every Go HTTP client, database driver, and gRPC stub already implements internally; threading the context through your own functions lets callers tighten or extend the deadline without changing your code.