===== WithValue ===== ==== What is it? ==== `context.WithValue(parent, key, val)` returns a child context that carries a key/value pair. Signature: `ctx := context.WithValue(parent, key, val)` ==== What is it used for? ==== * Carry **request-scoped** metadata like request-id, trace-id, user-id. * Pass small values across API boundaries when you cannot change function signatures. ==== Example (typed key) ==== type ctxKey string const requestIDKey ctxKey = "request_id" func WithRequestID(ctx context.Context, id string) context.Context { return context.WithValue(ctx, requestIDKey, id) } func RequestID(ctx context.Context) (string, bool) { v := ctx.Value(requestIDKey) s, ok := v.(string) return s, ok } ==== Notes / pitfalls (very important) ==== * Use `WithValue` sparingly. Prefer explicit parameters for business logic. * Keys should be custom types (not plain string) to avoid collisions. * Do NOT store large objects (DB connections, big structs) in context. * Values must be safe to access concurrently (context may be shared). ==== Related pages ==== * [[go:data_structures:type_assertion|Type assertion]] * [[go:data_structures:type_switch|Type switch]] * [[go:concurrency:context|context.Context]] ==== Hard words (English) ==== * **request-scoped** /rɪˈkwest skoʊpt/: gắn với 1 request * **metadata** /ˈmetəˌdeɪtə/: dữ liệu mô tả * **sparingly** /ˈsperɪŋli/: dùng hạn chế * **collision** /kəˈlɪʒən/: xung đột * **explicit** /ɪkˈsplɪsɪt/: tường minh * **concurrently** /kənˈkɝːəntli/: đồng thời