Context Values in Go

Carry request IDs and user information through a request with context.WithValue, and know what should stay a normal parameter.

A context can carry a few values that belong to one request, read anywhere down the call chain without changing function signatures.

Passing Request-Scoped Values

type userKey struct{}
ctx = context.WithValue(ctx, userKey{}, user)
u, ok := ctx.Value(userKey{}).(User)

Use unexported key types, wrap access in small helpers, and keep values to cross-cutting data like request and trace IDs.

Values are not parameters:

Anything a function cannot work without should be a parameter, so the compiler checks it.

Summary

Context values are for metadata that travels with a request, not for inputs or dependencies.

Passing Values with context.WithValue in Go

How context.WithValue works, why keys should be unexported types, what belongs in a context and what should be a normal function parameter.