Senior
A simple live coding task (basic concurrency) Condition: Write a function fetchAll(urls []string) map[string]string that performs HTTP GET requests concurrently for each URL and returns a map where the key is the URL and the value is the response body (string). If the request fails (error, not 200), the value should be an empty string. Constraints: - Do not use external libraries (only standard). - Do not change the signature. - The program should not crash on panic in http.Get. Example input: ["[link]" "[link]" "[link]"]
sobes.tech AI
Answer from AI
go package main
import ( "fmt" "io/ioutil" "net/http" "sync" )
func fetchAll(urls []string) map[string]string { results := make(map[string]string) var mu sync.Mutex var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func(u string) {
defer wg.Done()
// Handling panic in http.Get
defer func() {
if r := recover(); r != nil {
mu.Lock()
results[u] = ""
mu.Unlock()
}
}()
resp, err := http.Get(u)
if err != nil {
mu.Lock()
results[u] = ""
mu.Unlock()
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
mu.Lock()
results[u] = ""
mu.Unlock()
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
mu.Lock()
results[u] = ""
mu.Unlock()
return
}
mu.Lock()
results[u] = string(body)
mu.Unlock()
}(url)
}
wg.Wait()
return results
}
func main() { urls := []string{ "https://example.com", "https://golang.org", "https://invalid.url", } results := fetchAll(urls) for url, body := range results { fmt.Printf("URL: %s, Body length: %d\n", url, len(body)) } }