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()
}Report a problem with this exampleOpens a pre-filled issue on GitHub.