Skip to content

Context

Advanced · Concurrency

context.Context carries cancellation signals, deadlines, and request-scoped values across API boundaries and goroutines. Convention: pass it as the first argument, named ctx.

  • context1 — cancellation via context.WithCancel + ctx.Done()
  • context2 — timeouts via context.WithTimeout; return ctx.Err()
  • context3 — request-scoped values via WithValue / ctx.Value

A context.Context lets a caller signal cancellation to running work.

Show hint
A select can wait on multiple channels at once.
Add `case <-ctx.Done(): return count` so the loop exits when cancelled.

Source

context.WithTimeout cancels itself after a duration.

Show hint
Race the work against the context using select:
select {
case <-time.After(d): return nil
case <-ctx.Done(): return ctx.Err()
}

Source

Contexts can carry request-scoped values down a call chain.

Show hint
ctx.Value returns interface{}. Use the comma-ok type assertion:
if u, ok := ctx.Value(userKey).(string); ok { return u }
return "anonymous"

Source