Skip to content

Commit

Permalink
Merge pull request #1 from mseptiaan/main
Browse files Browse the repository at this point in the history
fix(client): fix parallel requests error handling
  • Loading branch information
zakirkun authored Dec 3, 2024
2 parents d516708 + 915fe74 commit c4ab184
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions tomoe.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log"
"net/http"
"net/url"
"sync"
"time"
)

Expand All @@ -25,11 +26,12 @@ func NewClient(baseURL string, timeout time.Duration, retries int, backoff time.
func (c *Client) ParallelRequests(ctx context.Context, opts []RequestOptions) ([]*http.Response, error) {
results := make([]*http.Response, len(opts))
errCh := make(chan error, len(opts))
doneCh := make(chan struct{}, len(opts))
var wg sync.WaitGroup

for i, opt := range opts {
wg.Add(1)
go func(i int, opt RequestOptions) {
defer func() { doneCh <- struct{}{} }()
defer wg.Done()
res, err := c.Do(ctx, opt)
if err != nil {
errCh <- err
Expand All @@ -39,15 +41,13 @@ func (c *Client) ParallelRequests(ctx context.Context, opts []RequestOptions) ([
}(i, opt)
}

// Wait for all requests to finish
for i := 0; i < len(opts); i++ {
<-doneCh
}
go func() {
wg.Wait()
close(errCh)
}()

// Check for errors
close(errCh)
if len(errCh) > 0 {
return nil, <-errCh
for err := range errCh {
return nil, err
}

return results, nil
Expand Down

0 comments on commit c4ab184

Please sign in to comment.