# 错误：net/http：请求被取消（客户端超时或上下文取消）

- **ID:** `go/net-http-request-canceled-by-client`
- **领域:** go
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

客户端因超时或显式上下文取消，在服务器响应前取消了HTTP请求。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.20 | active | — | — |
| 1.21 | active | — | — |

## 解决方案

1. **Use a custom context with proper timeout and cancellation handling** (90% 成功率)
   ```
   ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := client.Do(req)
if errors.Is(err, context.Canceled) { /* handle gracefully */ }
   ```

## 无效尝试

- **Increasing client timeout indefinitely without handling context** — Context cancellation can still occur from upstream, leading to same error; indefinite timeout is not scalable. (70% 失败率)
- **Ignoring the error and retrying blindly** — Retrying without checking context may amplify load and cause cascading failures. (80% 失败率)
