Senior
**Condition** Requests to multiple URLs should be executed in parallel. You need to output HTTP statuses and handle errors. ```go package main func main() { urls := []string{"[link]"} // Do something } ```
sobes.tech AI
Answer from AI
Below is a Go example that performs parallel HTTP requests to multiple URLs, outputs HTTP statuses, and handles errors:
package main
import (
"fmt"
"net/http"
"sync"
)
func main() {
urls := []string{
"https://golang.org",
"https://invalid.url",
"https://github.com",
}
var wg sync.WaitGroup
wg.Add(len(urls))
for _, url := range urls {
go func(u string) {
defer wg.Done()
resp, err := http.Get(u)
if err != nil {
fmt.Printf("Request error for %s: %v\n", u, err)
return
}
defer resp.Body.Close()
fmt.Printf("URL: %s, Status: %s\n", u, resp.Status)
}(url)
}
wg.Wait()
}
In this example:
sync.WaitGroupis used to wait for all goroutines to finish.- Each URL has a separate goroutine that makes an HTTP GET request.
- Errors are printed to the console.
- Successful requests print the HTTP status.