Senior
// Fix the code so that requests are concurrent and the response code is displayed // and in case of error - log it and continue processing package main import "net/http" var addrs = []string{"[link] "[link] "[link] "[link] "[link] "[link] "[link] func main() { wg := sync.WaitGroup{} data := make(map[string]bool) for _, url := range addrs { wg.Add(1) if !data[url]{ data[url] = true go func(url string){ defer wg.Done() resp, err := http.Get(url) if err != nil { log.err return } log.info }(url) } } wg.Wait() }
sobes.tech AI
Answer from AI
go package main
import ( "log" "net/http" "sync" )
var addrs = []string{ "https://example.com/1", "https://example.com/2", "https://example.com/3", "https://example.com/4", "https://example.com/5", "https://example.com/6", "https://example.com/7", }
func main() { wg := sync.WaitGroup{} data := make(map[string]bool) mu := sync.Mutex{} // for protecting the map
for _, url := range addrs {
mu.Lock()
if !data[url] {
data[url] = true
mu.Unlock()
wg.Add(1)
go func(url string) {
defer wg.Done()
resp, err := http.Get(url)
if err != nil {
log.Printf("Error requesting %s: %v", url, err)
return
}
defer resp.Body.Close()
log.Printf("Response from %s: %d", url, resp.StatusCode)
}(url)
} else {
mu.Unlock()
}
}
wg.Wait()
}
**Explanation:**
- A mutex `mu` is added for safe access to the `data` map from multiple goroutines.
- Checking and setting values in `data` occurs under mutex protection to avoid race conditions.
- Requests are executed concurrently in goroutines.
- In case of an error, a log with the error is output, but execution continues.
- The HTTP response status code is logged.
- `defer resp.Body.Close()` is used for proper closing of the response body.