Sobes.tech
Junior — Middle

How can multiple requests be combined into one or ensured to execute sequentially?

sobes.tech AI

Answer from AI

In Go, there are several approaches to combine multiple requests into one or ensure their sequential execution:

  1. Sequential execution: simply call the request functions one after another, waiting for each to complete before the next.
resp1, err := client.Do(req1)
if err != nil {
    // handle error
}
resp2, err := client.Do(req2)
// and so on
  1. Parallel execution with waiting: launch requests in goroutines and use sync.WaitGroup to wait for their completion.
var wg sync.WaitGroup
wg.Add(2)
go func() {
    defer wg.Done()
    client.Do(req1)
}()
go func() {
    defer wg.Done()
    client.Do(req2)
}()
wg.Wait()
  1. Combining requests: if the API supports it, you can combine multiple requests into one (for example, batch request), but this depends on the server.

Thus, the choice depends on the requirements: whether sequentiality or parallelism is needed, and whether the server supports request aggregation.

How can multiple requests be combined into one or… - sobes.tech