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.
Code
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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.