Avoiding collisions in Go context keys
Along with propagating deadlines and cancellation signals, Go’s context package can also carry request-scoped values across API boundaries and processes. There are only two public API constructs associated with context values: func WithValue(parent Context, key, val any) Context func (c Context) Value(key any) any The naive workflow to store and retrieve values in a context looks like this: ctx := context.Background() // Store some value against a key ctx = context.WithValue(ctx, "userID", 42) // Retrieve the value v := ctx.Value("userID") // Value returns any, so you need a type assertion id, ok := v.(int) if !ok { fmt.Println("unexpected type") } fmt.Println(id) // 42 WithValue returns a derived context that points to the parent context. ...