๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Go Context Values

Context values are small pieces of data stored inside a context. A function that receives the context can read the data back out.

Store a value and read it back

WithValue stores the name under the key "name". Value reads it back with the same key.

package main

import (
	"context"
	"fmt"
)

func main() {
	ctx := context.WithValue(context.Background(), "name", "Mina")
	fmt.Println(ctx.Value("name"))
}

Two key types hold two values

The keys nameKey and idKey are different types, so the same word can key two slots. Each Value call reads its own slot back.

package main

import (
	"context"
	"fmt"
)

type nameKey string

type idKey string

func main() {
	ctx := context.Background()
	ctx = context.WithValue(ctx, nameKey("item"), "notebook")
	ctx = context.WithValue(ctx, idKey("item"), 42)
	fmt.Println(ctx.Value(nameKey("item")))
	fmt.Println(ctx.Value(idKey("item")))
}

A missing key reads back nil

The context holds a name and nothing under the key "city". The read prints <nil>.

package main

import (
	"context"
	"fmt"
)

func main() {
	ctx := context.WithValue(context.Background(), "name", "Mina")
	fmt.Println(ctx.Value("city"))
}

Example

package main

import (
	"context"
	"fmt"
)

type requestKey string

func last(ctx context.Context) {
	fmt.Println("Request:", ctx.Value(requestKey("id")))
}

func middle(ctx context.Context) {
	last(ctx)
}

func first(ctx context.Context) {
	middle(ctx)
}

func main() {
	ctx := context.WithValue(context.Background(), requestKey("id"), "req-42")
	first(ctx)
}

Key points

  • Use context.WithValue to store a value inside a context.
  • WithValue returns a new context that carries the value.
  • The Value method reads a stored value back by its key.
  • A key is often a value of a named type made just for keys.
  • Two different key types can hold two values in one context.
  • A key that was never stored reads back as nil.

In this example, main stores the request id in the context under a key of the named type requestKey. First passes the context to middle, and middle passes it to last. Last reads the id back and prints it at the end of the chain.

Note

Context values suit small request data, not the main inputs of a function.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does ctx.Value return for a key that was never stored?