← 返回 Golang 列表

Go context 包与请求追踪

Context 传递超时、取消信号与请求 ID,实现分布式追踪上下文。

常用派生 Context

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

传递请求 ID

type key int
const requestIDKey key = 1

func WithRequestID(ctx context.Context, id string) context.Context {
  return context.WithValue(ctx, requestIDKey, id)
}
提示: Context 键使用自定义类型,避免冲突;不要在结构体里存 Context。