Junior — Middle
How can you perform five requests to the server simultaneously?
sobes.tech AI
Answer from AI
In Go, to perform multiple server requests concurrently, it is convenient to use goroutines and channels for synchronizing results. For example, you can launch 5 goroutines, each performing a request, and collect the results through a channel:
package main
import (
"fmt"
"net/http"
"sync"
)
func fetch(url string, wg *sync.WaitGroup, ch chan<- string) {
defer wg.Done()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprintf("Error fetching %s: %v", url, err)
return
}
ch <- fmt.Sprintf("%s: %s", url, resp.Status)
resp.Body.Close()
}
func main() {
urls := []string{
"http://example.com/1",
"http://example.com/2",
"http://example.com/3",
"http://example.com/4",
"http://example.com/5",
}
var wg sync.WaitGroup
ch := make(chan string, len(urls))
for _, url := range urls {
wg.Add(1)
go fetch(url, &wg, ch)
}
wg.Wait()
close(ch)
for msg := range ch {
fmt.Println(msg)
}
}
This approach allows for efficient execution of multiple requests in parallel.