Errgroup Parallel Fetch Fanout

Run parallel HTTP fetches with errgroup for concurrent fanout with first-error cancellation.

GoData Fetching

Code

gosnippet
20 lines
package main
import ("context";"golang.org/x/sync/errgroup";"net/http";"sync")
func fetchAll(ctx context.Context, urls []string) ([][]byte, error) {
    g, ctx := errgroup.WithContext(ctx)
    results := make([][]byte, len(urls))
    var mu sync.Mutex
    for i, url := range urls {
        i, url := i, url
        g.Go(func() error {
            req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
            resp, err := http.DefaultClient.Do(req)
            if err != nil { return err }
            defer resp.Body.Close()
            data, _ := io.ReadAll(resp.Body)
            mu.Lock(); results[i] = data; mu.Unlock()
            return nil
        })
    }
    return results, g.Wait()
}

Inside the snippet

Errgroup Parallel Fetch Fanout keeps everything in the function fetchAll.

Repetition is confined to for i, url := range urls — the rest of the file is straight-line. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Points of care

  • golang.org/x/sync/errgroup must be installed first — the snippet imports it directly.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

The entry-point signature is func fetchAll(ctx context.Context, urls []string) ([][]byte, error)

Key statements

if err != nil { return err }
results := make([][]byte, len(urls))
return results, g.Wait()

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
Are there third-party dependencies?
`golang.org/x/sync/errgroup` — install it with the package manager before running.