Context values and where they stop

A context also carries values: a request id, an authenticated user, a trace span. The mechanism is a small immutable chain of key and value pairs, and the rules around it are stricter than the API. A value belongs in a context when it crosses the boundary of one request and no function in between wants to know about it; everything a function needs to do its job is a parameter.

WithValue

WithValue returns a new context with one more pair; the parent is unchanged. Two calls produce a chain, and a lookup walks it from the child towards the root. The key is a value, not a string, and the type below gives the keys a name so a lookup cannot collide with another package's string key by accident.

package main import ( "context" "fmt" ) type key string func main() { ctx := context.WithValue(context.Background(), key("requestID"), "req-42") ctx = context.WithValue(ctx, key("user"), "ada") fmt.Println("request:", ctx.Value(key("requestID"))) fmt.Println("user:", ctx.Value(key("user"))) fmt.Println("missing:", ctx.Value(key("tenant"))) }

go build -o app main.go && ./app

request: req-42
user: ada
missing: <nil>

The second pair was added to the context the first call returned, so both are visible. The missing key returned a nil interface and the print showed <nil>; a real caller uses the two-value form, id, ok := ctx.Value(key("requestID")).(string), and treats a missing value as a bug rather than as an empty string.

Reading a value back

A helper that reads the value once keeps the type assertion in one place. The key type is an empty struct here, which is the idiomatic choice for a key that does not need a value: it is comparable, it costs no memory, and no other package can construct the same type by accident. An empty struct is also why the lookup is a type assertion and not a comparison of strings.

package main import ( "context" "fmt" ) type key struct{} func requestID(ctx context.Context) string { if id, ok := ctx.Value(key{}).(string); ok { return id } return "none" } func main() { ctx := context.WithValue(context.Background(), key{}, "req-7") fmt.Println("id:", requestID(ctx)) fmt.Println("empty:", requestID(context.Background())) }

go build -o app main.go && ./app

id: req-7
empty: none

The helper returns a documented default for the empty context, which is what a middleware that always sets the id makes unnecessary in production. A default of "none" in a log line is a small lie; a value of "" with a comment, or an explicit error, is usually better.

Keys have types

Two keys with the same text but different types are different keys, because a context compares keys by interface equality. The program below stores a string key and a struct key whose field is the same word, and the two lookups find their own values. That property is what keeps packages from overwriting each other's values.

package main import ( "context" "fmt" ) func main() { ctx := context.WithValue(context.Background(), "id", "string-key") ctx = context.WithValue(ctx, struct{ name string }{"id"}, "struct-key") fmt.Println("string:", ctx.Value("id")) fmt.Println("struct:", ctx.Value(struct{ name string }{"id"})) }

go build -o app main.go && ./app

string: string-key
struct: struct-key

A string key works and is discouraged: another package can use the same string and read or replace the value. The unexported type is the enforcement, because code outside the package cannot spell its type. A key must be comparable, so a slice or a map cannot be a key, and a key that holds a large struct compares the whole struct on every lookup.

A value survives cancellation

Cancellation and values travel independently: a cancelled child still carries the values of its parent, and a value added to a child is not visible to the parent. The program cancels the child immediately and still reads the id, which is what lets an error path log which request failed.

package main import ( "context" "fmt" ) type key string func main() { parent := context.WithValue(context.Background(), key("id"), "req-9") ctx, cancel := context.WithCancel(parent) cancel() fmt.Println("value:", ctx.Value(key("id"))) fmt.Println("error:", ctx.Err()) }

go build -o app main.go && ./app

value: req-9
error: context canceled

The value is there and the error says the context is done, and both are true. The rule that ties this together: a context value is for data that outlives any one function call of the request, such as an id, a user or a logger. A database handle, a mutex or a configuration object is a field of the type that needs it, not a value smuggled through the context.

Exercises

  1. Add the same key twice with different values and read it back. Which value wins, and why does the chain behave that way?
  2. Add a value to a child context and read it from the parent. What does the parent see, and what does that say about the direction of the chain?
  3. Replace the unexported key type with a plain string and write a second package that uses the same string. What could go wrong, and what stops it with the typed key?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does context.WithValue return?

    Answer

    A new context with one more key and value

    The parent context is unchanged.

  2. What does ctx.Value return for a missing key?

    Answer

    nil

    The two-value type assertion reports whether it was there.

  3. Why use an unexported type as a key?

    Answer

    So no other package can construct the same key

    The type is the namespace.

  4. What does a context compare keys by?

    Answer

    Interface equality, type and value

    Two keys with the same text but different types differ.

  5. What happens to the values when a child is cancelled?

    Answer

    They stay readable

    Cancellation and values are independent.

  6. Which value belongs in a context?

    Answer

    A request id or authenticated user

    It is request-scoped data that crosses calls.

  7. Which value does NOT belong in a context?

    Answer

    A required function parameter

    A parameter is written in the signature for a reason.

  8. Can a slice be a context key?

    Answer

    No, keys must be comparable

    A non-comparable key would panic on lookup.

  9. Which direction does a lookup walk the chain?

    Answer

    From the child towards the root

    The nearest value wins.

  10. What is the usual reason to pass a context to a function?

    Answer

    To cancel or bound the work it does

    Cancellation and deadlines are the primary job.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image