Errgroup Parallel Fetch Fanout
Run parallel HTTP fetches with errgroup for concurrent fanout with first-error cancellation.
Code
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()
}Report a problem with this exampleOpens a pre-filled issue on GitHub.