Go Reference ยท Concurrency and Context
The Go context package
Overview of Go's context package: Background, WithCancel, WithTimeout, WithDeadline, WithValue, cause functions, AfterFunc, and the rules for passing a Context.
The context package carries a cancellation signal, an optional deadline and a few request-scoped values across API boundaries and between goroutines. When a request is abandoned, a timeout expires or a parent operation is cancelled, every function that received the context can notice and stop early.
A Context is an immutable interface. You never modify one; you derive a child with WithCancel, WithTimeout, WithDeadline or WithValue. Cancelling a parent cancels all its children, but never the other way round.
ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
type Context interface { Deadline() (deadline time.Time, ok bool) Done() <-chan struct{} Err() error Value(key any) any } func Background() Context func TODO() Context func WithCancel(parent Context) (Context, CancelFunc) func WithTimeout(parent Context, d time.Duration) (Context, CancelFunc) func WithDeadline(parent Context, t time.Time) (Context, CancelFunc) func WithValue(parent Context, key, val any) Context
| Function | Description |
|---|---|
Background, TODO |
Empty root contexts. Use Background at the top of main, servers and tests; TODO as a visible placeholder. |
WithCancel |
Child with a cancel function. |
WithTimeout, WithDeadline |
Child cancelled after a duration or at a time. |
WithValue |
Child carrying one key/value pair. |
WithCancelCause, WithTimeoutCause, WithDeadlineCause, Cause |
Attach and read a custom error explaining the cancellation (Go 1.20 / 1.21). |
WithoutCancel(parent) |
Child that keeps the values but is never cancelled (Go 1.21). |
AfterFunc(ctx, f) |
Runs f in its own goroutine after ctx is done; returns a stop function (Go 1.21). |
Err() returns nil while the context is live, then context.Canceled or context.DeadlineExceeded (which wraps a timeout error whose Timeout() is true).
Usage notes
- Convention: pass the context as the first parameter, named
ctx. Never store a context in a struct field (except in short-lived request objects) and never passnil; usecontext.TODO()if unsure. - Always call
cancel, usually withdefer cancel(), as soon as the work is done. Otherwise the child stays registered with its parent and timers keep running.go vetchecks for a lost cancel function. - Cancellation is cooperative. Nothing is interrupted; your code must
selectonctx.Done()or call APIs that accept a context (http.NewRequestWithContext,database/sql...Contextmethods,exec.CommandContext). - Values are for request-scoped data such as trace IDs, not for optional function arguments. Use an unexported key type to avoid collisions.
- Inheritance: a child's deadline is never later than its parent's. Cancelling the parent cancels every descendant.
ctx.Done()ofBackgroundisnil, so aselecton it blocks forever; that is fine because it is never cancelled.