Parallel Fetch With errgroup

Fetch several resources concurrently with errgroup so the first error cancels the rest and the combined call fails fast.

GoData Fetching

Code

snippet
package golang

import (
	"context"
	"fmt"

	"golang.org/x/sync/errgroup"
)

func fetch(ctx context.Context, url string) (string, error) {
	if url == "" {
		return "", fmt.Errorf("empty url")
	}
	return "body(" + url + ")", nil
}

func FetchAll(ctx context.Context, urls []string) ([]string, error) {
	group, ctx := errgroup.WithContext(ctx)
	results := make([]string, len(urls))
	for i, url := range urls {
		i, url := i, url
		group.Go(func() error {
			body, err := fetch(ctx, url)
			if err != nil {
				return err
			}
			results[i] = body
			return nil
		})
	}
	if err := group.Wait(); err != nil {
		return nil, err
	}
	return results, nil
}