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

gosnippet
35 lines
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
}

What the code does

All of the logic lives in the functions fetch and FetchAll.

The one repetition in this snippet is the loop for i, url := range urls. Failures are values here: 2 sites check err and decide instead of letting one propagate.

What to watch for

  • Requires golang.org/x/sync/errgroup as a package; the snippet will not run without it.
  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Applying it

The signature to start reading at is func FetchAll(ctx context.Context, urls []string) ([]string, error)

Treat FetchAll as the API: import it, and ignore the supporting code.

Statements that matter most here

func fetch(ctx context.Context, url string) (string, error) {
if url == "" {
return "", fmt.Errorf("empty url")
}
return "body(" + url + ")", nil
}
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
})
}
results := make([]string, len(urls))

Interactive Tools for This Topic

FAQ

What happens when a call fails?
The Go way: `err` comes back from each call, and 2 checkpoints here test it before proceeding.
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.