go network_error ai_generated true

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

ID: go/goroutine-leak-http-request

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-10-07First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.21 active — — —
1.22 active — — —

Root Cause

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

generic

中文

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

Workarounds

  1. 95% success
    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% success
    client := &http.Client{Timeout: 5 * time.Second}
    resp, err := client.Get(url)

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 90% fail

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