go network_error ai_generated true

错误:net/http:请求被取消(等待响应头时超过客户端超时)

error: net/http: request canceled (Client.Timeout exceeded while awaiting headers)

ID: go/goroutine-leak-http-request

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-10-07首次发现

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.21 active — — —
1.22 active — — —

根因分析

未带上下文或超时的 HTTP 客户端调用无限阻塞,导致 goroutine 泄漏,最终被客户端超时取消。

English

An HTTP client call without a context or timeout blocked indefinitely, leaving the goroutine leaked and the request canceled by the client timeout.

generic

解决方案

  1. 95% 成功率
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    resp, err := http.DefaultClient.Do(req)
  2. 90% 成功率
    client := &http.Client{Timeout: 5 * time.Second}
    resp, err := client.Get(url)

无效尝试

常见但无效的做法:

  1. 70% 失败

    Leaks the goroutine longer; the root cause is missing cancellation.

  2. 90% 失败

    http.Get uses DefaultClient with no timeout; can block forever.