I want to use a map's keys to request something from an API and then update the corresponding values based on the API's response.
My guess would be the following code.
Or maybe scratch this approach, collect the map-keys in an array before iterating and then use the array entries to make a request and modify the map
wg := &sync.WaitGroup{}
wg.Add(len(someMap))
sem := semaphore.NewWeighted(maxWorkers)
ctx := context.TODO()
mutex := &sync.RWMutex{}
mutex.RLock()
for k, v := range someMap {
mutex.RUnlock()
go func(k, v) {
defer wg.Done()
sem.Acquire(ctx, 1)
res, err := API.REQUEST(k)
sem.Release(1)
if err != nil {
return
}
v.SomeElement = res.SomeElement
mutex.Lock()
someMap[k] = v
mutex.Unlock()
}(k, v)
mutex.RLock()
}
mutex.RUnlock()
wg.Wait()