typestar

Context values in Go

A context can carry request-scoped values, keyed by an unexported type.

type contextKey struct{ name string }

var requestIDKey = contextKey{"requestID"}

func withRequestID(ctx context.Context, id string) context.Context {
    return context.WithValue(ctx, requestIDKey, id)
}

func requestID(ctx context.Context) (string, bool) {
    id, ok := ctx.Value(requestIDKey).(string)
    return id, ok
}

func demo() (string, bool) {
    ctx := withRequestID(context.Background(), "abc123")
    return requestID(ctx)
}

How it works

  1. A private key type stops two packages colliding.
  2. Values are for request metadata, not for passing arguments.
  3. The lookup returns any, so it needs a type assertion.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
421
Tokens
102
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 3 of 3 in Context, step 13 of 25 in Concurrency.

← Previous Next →