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,语义更清晰单个请求卡住会拖慢整个批次。务必用 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
避免多个 goroutine 写同一 slice 引发竞态。建议定义结构体封装结果,并用 channel 统一接收:
type Result struct {
URL string
Data []byte
Err error
Status int
}Result 发到同一个 chan Result
for i := 0; i 循环接收,确保收齐
done channel 或 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./link/5f69e19efaba426d62faeab93c308f5c", "https://www./link/ef246753a70fce661e16668898810624", "https://www./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、重试、熔断等。