Table of Contents

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?

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)

Hard words (English)