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; returnctx.Err() - context3 — request-scoped values via
WithValue/ctx.Value
Resources
Section titled “Resources”Exercises
Section titled “Exercises”context1 test
Section titled “context1 test”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.context2 test
Section titled “context2 test”context.WithTimeout cancels itself after a duration.
Show hint
Race the work against the context using select:
select {case <-time.After(d): return nilcase <-ctx.Done(): return ctx.Err()}context3 test
Section titled “context3 test”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"