Use errgroup to run multiple goroutines concurrently while automatically canceling remaining tasks if any one fails. Create a group with WithContext, launch tasks using g.Go, and wait for completion with g.Wait to retrieve the first error.
package main
import (
"context"
"fmt"
"time"
"golang.org/x/sync/errgroup"
)
func main() {
ctx := context.Background()
g, ctx := errgroup.WithContext(ctx)
for i := 0; i < 3; i++ {
i := i
g.Go(func() error {
time.Sleep(time.Second)
if i == 1 {
return fmt.Errorf("task %d failed", i)
}
fmt.Printf("task %d done\n", i)
return nil
})
}
if err := g.Wait(); err != nil {
fmt.Println("Error:", err)
}
}