Errgroup Context Cancellation HTTP
Run parallel HTTP fetches under one errgroup context so the first error cancels siblings and always reclaims goroutines.
Code
package main
import (
"context"
"fmt"
"net/http"
"golang.org/x/sync/errgroup"
)
type Result struct {
URL string
Code int
}
func fetchAll(ctx context.Context, urls []string) ([]Result, error) {
g, ctx := errgroup.WithContext(ctx)
results := make([]Result, len(urls))
for i, url := range urls {
i, url := i, url // 捕获循环变量(Go 1.22 前必需)
g.Go(func() error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("build request %s: %w", url, err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("fetch %s: %w", url, err)
}
defer resp.Body.Close()
results[i] = Result{URL: url, Code: resp.StatusCode}
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err // ctx 已取消,其余 goroutine 全部提前退出
}
return results, nil
}
func main() {
rs, err := fetchAll(
context.Background(),
[]string{"https://example.com/a", "https://example.com/b"},
)
fmt.Println(len(rs), err)
}How it works
Everything happens inside the functions fetchAll and main.
The cycling part of this snippet is for i, url := range urls. err is inspected at 3 call sites before any result is trusted. The function registers its cleanup up front with defer, so no exit path forgets it.
What to watch for
- Dependency check:
golang.org/x/sync/errgroup— not built-in, must be present in the project. - Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Applying it
The main signature appears as func fetchAll(ctx context.Context, urls []string) ([]Result, error)
Treat main as the orchestrator calling fetchAll in a fixed order.
Statements that matter
return fmt.Errorf("build request %s: %w", url, err)
return fmt.Errorf("fetch %s: %w", url, err)
func main() {
rs, err := fetchAll(
context.Background(),
[]string{"https://example.com/a", "https://example.com/b"},
)
fmt.Println(len(rs), err)
}
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- How are errors reported?
- By return value: each fallible call hands back an `error`, checked at 3 places here.
- What does this need from the package registry?
- These are real dependencies: `golang.org/x/sync/errgroup`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.