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

context.WithTimeout 为什么没让 HTTP 请求提前取消?
Go 的 http.Client 默认不读取 context 的取消信号,必须显式传入带 context 的方法(如 Do),否则 WithTimeout 或 WithCancel 对请求本身无效。
- 错误写法:
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.WithCancel 或 context.WithTimeout 构造真实可触发的 context,而非 mock。mock context 无法触发底层 goroutine 唤醒机制,容易掩盖泄漏问题。
立即学习“go语言免费学习笔记(深入)”;
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配合延迟响应,而不是依赖外部服务
Done() —— 少一个 select,就可能埋下 goroutine 泄漏的种子。










