Files
bulma/context_value.go
T

45 lines
883 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
"fmt"
)
// 自定义键类型,防止键名冲突
type ctxKey string
// 定义上下文键常量
const (
TraceID ctxKey = "trace_id"
UserID ctxKey = "user_id"
)
// 业务处理函数:从上下文获取元数据
func handleRequest(ctx context.Context) {
// 安全类型断言获取值
traceID, ok := ctx.Value(TraceID).(string)
if !ok {
fmt.Println("未获取到追踪ID")
return
}
userID, ok := ctx.Value(UserID).(int)
if !ok {
fmt.Println("未获取到用户 ID")
return
}
fmt.Printf("请求处理中:TraceID=%sUserID=%d\n", traceID, userID)
}
func main() {
// 初始化根上下文
ctx := context.Background()
// 存入请求链路元数据
ctx = context.WithValue(ctx, TraceID, "20260324-CTX-001")
ctx = context.WithValue(ctx, UserID, 10000) // int
// 传递上下文到业务函数
handleRequest(ctx)
}