Context values
Request-scoped data carried in a context.Context with context.WithValue. Use an unexported key type so no other package can collide with or forge the key, and read it through one typed accessor. Contexts are immutable: WithValue returns a new one.
Minimal example
type ctxKey struct{}
ctx := context.WithValue(r.Context(), ctxKey{}, principal)
p, ok := ctx.Value(ctxKey{}).(Principal)Learn this concept
Lesson 3.4 · Bearer middleware and request contextUsed in exercises
Exercise 3.5 · GET /v1/me: caller account Exercise 3.10 · POST /v1/orders: idempotent checkout Exercise 3.12 · POST /v1/orders/{id}/events: order lifecycle Exercise 6.6 · Request context and timeout layerRelatedHTTP middleware