Go 并发 HTTP 请求需控制并发数(20–50)、使用 context 统一超时、通过 channel 安全收集结果;避免盲目启大量 goroutine,推荐 semaphore 或带缓冲 channel 限流,并用结构体封装结果防止竞态。

用 Go 实现并发 HTTP 请求,核心是结合 goroutine 和 channel 控制并发流程,同时避免资源耗尽和超时堆积。关键不是“越多越快”,而是合理控制并发数、统一处理错误与超时、安全收集结果。
控制并发数量,防止压垮服务或自身
直接为每个请求起一个 goroutine 容易失控(比如 1000 个 URL 启 1000 个 goroutine),推荐使用带缓冲的 channel 或 semaphore 模式限制并发数:
- 用
make(chan struct{}, N)作为信号量:每次发请求前先写入一个占位符,请求结束再读出,自然限流 - 或用第三方库如
golang.org/x/sync/semaphore,语义更清晰 - 常见合理值:20–50(取决于目标接口承载力和本地网络/文件描述符限制)
每个请求必须带上下文(context)超时
单个请求卡住会拖慢整个批次。务必用 context.WithTimeout 或 context.WithDeadline 包裹请求:
- 不要只靠
http.Client.Timeout,它不覆盖 DNS 解析、TLS 握手等阶段 - 推荐写法:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second),并在 defer 中调用cancel() - 把
ctx传给http.NewRequestWithContext,再交给client.Do
用 channel 安全收集结果,区分成功与失败
避免多个 goroutine 写同一 slice 引发竞态。建议定义结构体封装结果,并用 channel 统一接收:
立即学习“go语言免费学习笔记(深入)”;
type Result struct {
URL string
Data []byte
Err error
Status int
}- 启动 N 个 goroutine,每个做完后把
Result发到同一个chan Result - 主 goroutine 用
for i := 0; i 循环接收,确保收齐 - 可额外加一个
donechannel 或sync.WaitGroup辅助判断完成
完整轻量示例(无依赖,开箱即用)
以下代码并发请求 3 个 URL,最大并发 2,每请求 3 秒超时:
func fetchURL(ctx context.Context, url string, sem chan struct{}) Result {
sem <- struct{}{} // 获取令牌
defer func() { <-sem }() // 释放令牌
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Do(req)
if err != nil {
return Result{URL: url, Err: err}
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
return Result{URL: url, Data: data, Status: resp.StatusCode}}
func main() {
urls := []string{"https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c", "https://www.php.cn/link/ef246753a70fce661e16668898810624", "https://www.php.cn/link/8c4b0479f20772cb9b68cf5f161d1e6f"}
sem := make(chan struct{}, 2)
ch := make(chan Result, len(urls))
for _, u := range urls {
go func(url string) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
ch <- fetchURL(ctx, url, sem)
}(u)
}
results := make([]Result, 0, len(urls))
for i := 0; i < len(urls); i++ {
results = append(results, <-ch)
}
for _, r := range results {
if r.Err != nil {
fmt.Printf("❌ %s → %v\n", r.URL, r.Err)
} else {
fmt.Printf("✅ %s → %d bytes, status %d\n", r.URL, len(r.Data), r.Status)
}
}}
不复杂但容易忽略细节:限流、上下文、结果收集三者缺一不可。实际项目中可进一步封装成可复用函数,支持自定义 Header、重试、熔断等。










