Parallel Fetch With errgroup
Fetch several resources concurrently with errgroup so the first error cancels the rest and the combined call fails fast.
Code
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/errgroupas a package; the snippet will not run without it. - Errors are ordinary return values; skipping the
errcheck 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
cURL to fetch ConverterTranslate a curl command into equivalent JavaScript fetch() code, handling the request method, headers, JSON or raw body, and basic auth.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.