Context Package
Request-scoped deadlines, cancellation, and values. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Request-scoped deadlines, cancellation, and values. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Manual cancel signal.
ctx, cancel := context.WithCancel(context.Background())
cancel()
ctx.Err() // context.CanceledAuto-cancel after duration.
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()
<-ctx.Done()
errors.Is(ctx.Err(), context.DeadlineExceeded) // trueStore request-scoped data - use typed keys.
type key int
const userKey key = 0
ctx := context.WithValue(context.Background(), userKey, "ada")
ctx.Value(userKey) // "ada"Check why context ended.
ctx, cancel := context.WithCancel(context.Background())
cancel()
errors.Is(ctx.Err(), context.Canceled) // trueBackground is root; TODO is placeholder.
context.Background() != nil // trueCancel at absolute time.
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Hour))
defer cancel()
ctx.Err() == nil // true until deadlineWait for cancel or work.
ctx, cancel := context.WithCancel(context.Background())
cancel()
select {
case <-ctx.Done():
errors.Is(ctx.Err(), context.Canceled) // true
}Context is first param by convention.
// func Load(ctx context.Context, id string) errorDo not store Context inside long-lived structs - pass as param.
// prefer func (s *Svc) Get(ctx context.Context, id string)Derive from request.
// ctx := r.Context()WithCancelCause for richer cancel reasons.
// ctx, cancel := context.WithCancelCause(parent)
// cancel(fmt.Errorf("reason"))Using Background mid-stack loses cancel - pass parent ctx.
// wrong: context.Background() inside library helpersChild timeouts should be shorter than parent when nested.
// parent 5s, child WithTimeout(parent, time.Second)Run function after cancel (Go 1.21+).
// stop := context.AfterFunc(ctx, func() { ... })Private key types avoid collisions.
type ctxKey struct{}
ctx := context.WithValue(context.Background(), ctxKey{}, 1)
ctx.Value(ctxKey{}) // 1Stack versions: Go 1.26.x · chi/gin/echo latest (verify at build)
Reviewed by Chris St. John·Last updated Jul 18, 2026