Errgroup Parallel API Fanout
Fan out parallel API calls with errgroup and limit concurrency in Go services.
Code
package main
import ("context";"golang.org/x/sync/errgroup";"net/http";"io")
func fanoutAPI(ctx context.Context, urls []string, limit int) ([][]byte, error) {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(limit)
results := make([][]byte, len(urls))
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()
results[i], _ = io.ReadAll(resp.Body)
return nil
})
}
return results, g.Wait()
}The shape of the execution
Errgroup Parallel API Fanout reduces to the function fanoutAPI.
One loop does the cycling here: for i, url := range urls. 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.
What to watch for
- Requires
golang.org/x/sync/errgroupas a package; the snippet will not run without it. - Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Applying it
Entry signature: func fanoutAPI(ctx context.Context, urls []string, limit int) ([][]byte, error)
Statements that matter
if err != nil { return err }
results := make([][]byte, len(urls))
return results, g.Wait()
FAQ
- Is there exception handling?
- No exceptions — `error` returns checked at 1 site, and callers branch on `err` first.
- Do I need to install anything before running this?
- Yes: `golang.org/x/sync/errgroup` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.