Typed Keys Store Context Values

Attach request-scoped data with context.WithValue, keyed by an unexported struct type so package boundaries cannot collide and lookups stay type-safe.

GoAuth Jwt

Code

snippet
package main

import (
	"context"
	"fmt"
)

// userKey 是未导出的自定义类型:类型不同即键不同,跨包也不会撞键
type userKey struct{}

func main() {
	ctx := context.Background()

	// 存入请求级数据:键必须是可比较类型,惯例用空结构体
	ctx = context.WithValue(ctx, userKey{}, "alice")

	// 取值时断言回具体类型:Value 沿父级 ctx 逐层查找
	if user, ok := ctx.Value(userKey{}).(string); ok {
		fmt.Println("user:", user)
	} else {
		fmt.Println("user: <none>")
	}

	// 换一个键(字符串与 userKey 类型不同)就查不到:ok=false,不会串数据
	if user, ok := ctx.Value("userKey").(string); ok {
		fmt.Println("string key hit:", user)
	} else {
		fmt.Println("string key: missing")
	}
}

What happens when it runs

Everything happens inside the function main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The signature doing the work: func main()

The demo output is labeled (user:, user: <none>, string key hit:), so each printed line traces to the operation that produced it.

Key statements

ctx = context.WithValue(ctx, userKey{}, "alice")
ctx := context.Background()

Interactive Tools for This Topic

FAQ

What does Typed Keys Store Context Values print when run?
Execute the whole file; each printed line is prefixed with a label like `user:`, `user: <none>`, `string key hit:`.