信息发布→ 登录 注册 退出

Golang使用context控制请求生命周期

发布时间:2026-01-10

点击量:
context.WithTimeout 未取消 HTTP 请求是因为 http.Client 默认不读取 context,需用 http.NewRequestWithContext 构造请求并调用 client.Do(req);http.Client.Timeout 控制整个请求生命周期,而 WithTimeout 仅控制调用方等待时间。

context.WithTimeout 为什么没让 HTTP 请求提前取消?

Go 的 http.Client 默认不读取 context 的取消信号,必须显式传入带 context 的方法(如 Do),否则 WithTimeoutWithCancel 对请求本身无效。

  • 错误写法:resp, err := http.DefaultClient.Get("https://api.example.com") —— 完全忽略 context
  • 正确写法:用 client.Do(req),且 req 必须由 http.NewRequestWithContext(ctx, ...) 构造
  • 注意 http.Client.Timeout 是整个请求生命周期(含 dial、TLS、read),而 context.WithTimeout 控制的是调用方等待时间,二者作用域不同,不要混用

中间件里如何把 request context 透传到 handler?

HTTP handler 接收的 *http.Request 已自带 context(r.Context()),但这个 context 是只读的;若需注入值(如用户 ID、trace ID),要用 context.WithValue 并配合 req.WithContext 覆盖:

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        userID := extractUserID(r.Header)
        ctx := context.WithValue(r.Context(), "user_id", userID)
        r = r.WithContext(ctx) // 必须重新赋值 r
        next.ServeHTTP(w, r)
    })
}
  • context.WithValue 的 key 建议用自定义类型(避免字符串冲突),例如 type ctxKey string; const userIDKey ctxKey = "user_id"
  • 不要在 context 中传大结构体或指针,它设计用于传递轻量元数据
  • handler 内通过 r.Context().Value(userIDKey) 获取,类型断言要检查是否为 nil

goroutine 泄漏常因 context.Done() 没被监听

启动子 goroutine 时若未 select 监听 ctx.Done(),即使父 context 被 cancel,子 goroutine 仍可能永久运行,尤其在循环或 channel 操作中。

  • 典型错误:启动 goroutine 后直接 go doWork(),没传 context 也没监听取消
  • 正确模式:所有长时操作(如轮询、channel recv)必须包裹在 select 中,包含 case
  • 注意:对已关闭 channel 的 recv 不会阻塞,但若 channel 未关且无 sender,recv 会永远阻塞——此时仅靠 context 无法唤醒,需配合 default 或带超时的 select

测试 context 取消逻辑该 mock 还是 real cancel?

单元测试中应使用 context.WithCancelcontext.WithTimeout 构造真实可触发的 context,而非 mock。mock context 无法触发底层 goroutine 唤醒机制,容易掩盖泄漏问题。

func TestFetchWithTimeout(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
    defer cancel()

    result, err := fetchData(ctx) // 内部调用 http.Do 并监听 ctx.Done()
    if err != context.DeadlineExceeded {
        t.Fatal("expected timeout error")
    }
}
  • 避免用 context.TODO()context.Background() 写测试,它们无法被 cancel
  • 如果被测函数内部创建了新 context(如 WithTimeout),需确保其父 context 可控,否则测试无法驱动取消路径
  • 真实网络调用建议用 httptest.Server 配合延迟响应,而不是依赖外部服务
context 的核心不是“加个参数”,而是整条调用链上每个阻塞点都得主动响应 Done() —— 少一个 select,就可能埋下 goroutine 泄漏的种子。
标签:# channel  # 中应  # 其父  # 都得  # 而非  # 自带  # 自定义  # 要用  # 也没  # 是因为  # 的是  # https  # http  # go  # nil  # 指针  # 循环  # 结构体  # 字符串  # const  # select  # String  # 中间件  # 为什么  # 作用域  # golang  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!