go network_error ai_generated true

Get "https://api.example.com/data":上下文截止时间已超过

Get "https://api.example.com/data": context deadline exceeded

ID: go/http-request-canceled-context

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

版本兼容性

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

根因分析

http.Client 请求的上下文在服务器响应前超时或被取消。常见原因:context.WithTimeout 设置过短、上游过慢,或在多个请求间复用了已取消的 context。

English

The http.Client request context timed out or was canceled before the server responded. Often caused by a too-short context.WithTimeout, a slow upstream, or reusing a canceled context across requests.

generic

解决方案

  1. 90% 成功率
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    resp, err := client.Do(req)
  2. 80% 成功率
    Use context.WithoutCancel(parentCtx) when a downstream call must outlive the parent request lifetime.

无效尝试

常见但无效的做法:

  1. 70% 失败

    If the deadline comes from the request context, the client Timeout is irrelevant; the context still fires first.

  2. 85% 失败

    Retrying with the same canceled context immediately fails again and amplifies load.