Go context.Context 到底该怎么用

TL;DR:context 只做三件事——取消信号、超时控制、请求域数据。 把它当「参数袋」用就是反模式。

为什么需要 context

一个 HTTP 请求背后可能派生了十几个 goroutine:查数据库、调下游 RPC、写日志。 当客户端断开连接时,这些 goroutine 应该全部被终止,否则就是资源泄漏。

取消信号的传播

context.WithCancel 返回的 cancel 函数一旦被调用,所有从它派生的子 context 都会收到取消信号:

go
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // 即使正常退出也要调用,避免 resource leak

go func() {
    time.Sleep(100 * time.Millisecond)
    cancel() // 触发取消
}()

select {
case <-ctx.Done():
    fmt.Println("canceled:", ctx.Err())
case <-time.After(time.Second):
    fmt.Println("done normally")
}

超时的两种写法

超时本质上也是取消信号,只是由内部定时器代为触发。区别如下:

API触发条件典型场景
WithTimeout 到达截止时间 单次 RPC 调用,3s 超时
WithDeadline 到达绝对时间点 批处理任务需在午夜前结束

Value 的正确使用姿势

只放「请求域数据」(request-scoped),如 trace ID、认证后的用户身份。 不要用它传递业务参数,那会让函数签名失去类型安全:

go
type ctxKey struct{}

func WithRequestID(ctx context.Context, id string) context.Context {
    return context.WithValue(ctx, ctxKey{}, id)
}

func RequestID(ctx context.Context) string {
    id, _ := ctx.Value(ctxKey{}).(string)
    return id
}

小结

  • context 作为函数第一个参数传递,命名 ctx
  • 不要存 struct 指针到 Value 里「绕过」参数传递
  • 每个 WithCancel / WithTimeout 都要配对调用 cancel,用 defer 最省心