Go context: cancellation, deadlines and request values
Short answer
A context.Context carries a deadline, a cancellation signal and request-scoped values across API boundaries and goroutines. Pass it as the first argument (ctx) to every function that needs it; do not store it in a struct. [S1][S2]
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
select { case <-ctx.Done(): return ctx.Err(); case r := <-results: return r }
Key points
Done()returns a channel closed when the context is canceled. [S1]- When a request is canceled or times out, all goroutines working on it should stop. [S1]
Claims
- id: C1 claim: A Context carries a deadline, cancellation signal, and request-scoped values. source: S1 evidence: "A Context carries a deadline, cancellation signal, and request-scoped values"
- id: C2 claim: Done returns a channel closed when the Context is canceled. source: S1 evidence: "Done returns a channel that is closed when this Context is canceled"
- id: C3 claim: Contexts should not be stored inside a struct type. source: S2 evidence: "Contexts should not be stored inside a struct type"
- id: C4 claim: The first argument is often context.Context. source: S2 evidence: "the first argument to functions and methods is often context.Context"
Sources
- [S1] Go Concurrency Patterns: Context - The Go Programming Language. The Go Authors (go.dev). https://go.dev/blog/context . License: CC BY 4.0 (go.dev text). Accessed 2026-11-04.
- [S2] Contexts and structs - The Go Programming Language. The Go Authors (go.dev). https://go.dev/blog/context-and-structs . License: CC BY 4.0 (go.dev text). Accessed 2026-11-04.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: The Go Authors (go.dev), Go Concurrency Patterns: Context - The Go Programming Language, CC BY 4.0 (go.dev text); The Go Authors (go.dev), Contexts and structs - The Go Programming Language, CC BY 4.0 (go.dev text).
Cite this
iinventedlight. 2026. "Go context: cancellation, deadlines and request values." iinventedlight Library, iil:note:crxzvtds, version of 2026-11-04. https://iinventedlight.com/library/notes/go-context/. License: CC-BY-4.0.
@misc{iil_note_crxzvtds,
author = {{iinventedlight}},
title = {{Go context: cancellation, deadlines and request values}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-04},
url = {https://iinventedlight.com/library/notes/go-context/},
note = {Permanent ID iil:note:crxzvtds. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.
For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/go-context.md.