Pass request metadata responsibly
Pass request metadata responsibly
Use context.WithValue for request-scoped metadata that needs to travel across API boundaries, such as an opaque request identifier. Do not use it for ordinary configuration, required function arguments or mutable shared state. Context values are looked up by comparable keys; prefer an unexported custom key type to avoid collisions between packages.
package main
import ( "context" "fmt")
type requestKey struct{}
func requestID(ctx context.Context) (string, bool) { v, ok := ctx.Value(requestKey{}).(string) return v, ok}func main() { root := context.Background() ctx := context.WithValue(root, requestKey{}, "req-42") fmt.Println(requestID(ctx)) fmt.Println(requestID(root))}WithValue derives a context; root is unchanged. A missing value returns nil, so a checked type assertion avoids panic and indicates absence. The second output starts with a space because the missing string is empty. A context value is not automatically serialized to another process. Forward only approved metadata explicitly at a network boundary.
Expected output:
req-42 true falseKeep ordinary options explicit
package main
import ( "context" "fmt")
type traceKey struct{}
func label(ctx context.Context, prefix string) string { id, _ := ctx.Value(traceKey{}).(string) return prefix + id}func main() { ctx := context.WithValue(context.Background(), traceKey{}, "42") fmt.Println(label(ctx, "job-")) fmt.Println(label(ctx, "task-"))}prefix is an explicit argument; the request identifier travels with ctx. Do not put secrets into context values just to make them accessible everywhere, or treat a request ID as proof of authorization. Context methods are concurrency-safe, but a map or pointer stored as a value still needs its own synchronization if mutated.
Expected output:
job-42task-42Try it locally
Define an unexported key type and a function tenant(ctx) (string,bool) using a checked assertion. Use synthetic tenant label "demo"; print successful lookup and whether a lookup from the root succeeds (false).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 07: Pass request metadata responsibly
Check the lesson objective before moving on.
What belongs in a context value?
Why use a private custom key type?