45 lines
883 B
Go
45 lines
883 B
Go
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=%s,UserID=%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)
|
||
}
|