ErrGroup Parallel Fan Out With Limits
Fan out work across goroutines with errgroup and SetLimit so failures propagate on first error while concurrency stays bounded.
Code
package main
import (
"fmt"
"golang.org/x/sync/errgroup"
)
func fetch(url string) (string, error) {
if url == "bad" {
return "", fmt.Errorf("fetch %q: unavailable", url)
}
return "body-of-" + url, nil
}
func main() {
urls := []string{"a", "b", "bad", "d", "e"}
// SetLimit(2):同时在飞的任务数上限;Wait 返回第一个非 nil 错误
g, ctx := errgroup.WithContext(context.Background())
g.SetLimit(2)
results := make([]string, len(urls))
for i, url := range urls {
i, url := i, url
g.Go(func() error {
// ctx 在任一任务失败后被取消,后续任务可提前退出
select {
case <-ctx.Done():
return ctx.Err()
default:
}
body, err := fetch(url)
if err != nil {
return err
}
results[i] = body
return nil
})
}
if err := g.Wait(); err != nil {
fmt.Println("failed:", err)
return
}
fmt.Println("all fetched:", results)
}Inside the flow
The snippet is organized around the functions fetch and main.
Repetition is confined to for i, url := range urls — the rest of the file is straight-line. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Watch out for
- External dependency:
golang.org/x/sync/errgroup— install it before running the snippet. - No panic path here — failures come back as
errorvalues that each caller must handle.
Using it
Signature: func fetch(url string) (string, error)
Running the file prints labeled results such as failed:, all fetched: — each operation’s effect is visible in the output.
main sequences fetch; executing the file runs that flow once.
Key statements
return "", fmt.Errorf("fetch %q: unavailable", url)
return ctx.Err()
if err != nil {
return err
}
Interactive Tools for This Topic
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- How should callers handle failures?
- As returned `error` values — 2 sites in the snippet check `err` before using other results.
- Does this require external packages?
- Yes — `golang.org/x/sync/errgroup`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.