← All notes

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

Claims

Sources

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

Permanent ID: iil:note:crxzvtds

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.},
}

Markdown

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.