Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Concurrency and Context

Go context.WithValue() function

Reference for Go context.WithValue: attach request-scoped data to a context, define collision-safe key types, read values with Value, and know what not to store.

context.WithValue returns a child context that carries one key/value pair. Anything that receives the context, however deep in the call chain, can read the value back with ctx.Value(key). It is meant for data that belongs to a single request or operation and crosses API boundaries: a request ID, an authenticated user, a trace span.

The lookup walks up the chain of parents until it finds a matching key, so a child sees everything its ancestors carry. Values are immutable: to "change" one you derive a new child with the same key.

Go
type ctxKey struct{}
ctx := context.WithValue(parent, ctxKey{}, "req-42")

Try it

Go A typed key and helper functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Shadowing and key collisions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func WithValue(parent Context, key, val any) Context
Name Description
parent Context to derive from; must not be nil.
key Any comparable value. Use your own unexported type to avoid collisions.
val Any value.

Returns. A new context whose Value(key) returns val; other lookups defer to the parent.

Panics. WithValue panics if parent is nil, if key is nil, or if key is not comparable (for example a slice).

Usage notes

  • Use a private key type. A plain string or int key can collide with keys from other packages. A struct type such as type userKey struct{} (or type key string in an unexported package) cannot. go vet and linters flag built-in key types.
  • Wrap access in functions (WithUser, UserFrom) so callers never touch the key or assert the type themselves.
  • Only request-scoped data. Good: request ID, auth identity, locale, trace info. Bad: database handles, loggers you configure at startup, optional function parameters. Those belong in struct fields or explicit arguments, where the compiler can see them.
  • Values are untyped and invisible. A function that reads a value from the context has a hidden dependency; keep such reads to middleware and a few well-named helpers.
  • Lookup is linear in the depth of the chain. Don't add dozens of values; store one struct instead.
  • Cancellation and values are independent. context.WithoutCancel(ctx) (Go 1.21) keeps the values but detaches from cancellation, handy for background work started by a request.