Sobes.tech
Middle+

func FetchAll(ctx context.Context, urls []string, concurrency int) ([]Result, error) { // Your code here return nil, nil }

sobes.tech AI

Answer from AI

go func FetchAll(ctx context.Context, urls []string, concurrency int) ([]Result, error) { type resultWithError struct { res Result err error }

results := make([]Result, len(urls))
ch := make(chan resultWithError)
sem := make(chan struct{}, concurrency) // limit by concurrency

for i, url := range urls {
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    case sem <- struct{}{}: // occupy a slot
    }

    go func(i int, url string) {
        defer func() { <-sem }() // free the slot
        res, err := Fetch(ctx, url) // assuming Fetch function
        ch <- resultWithError{res, err}
    }(i, url)
}

for i := 0; i < len(urls); i++ {
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    case r := <-ch:
        if r.err != nil {
            return nil, r.err
        }
        results[i] = r.res
    }
}

return results, nil

}


This code runs up to `concurrency` goroutines for parallel data fetching from URLs, using a context for cancellation. The results are collected into the `results` slice.
func FetchAll(ctx context.Context, urls []string… - sobes.tech