// Chapter 46 example: fetching several URLs at the same time. // Start the Chapter 45 server first, in another terminal, or pass your own URLs. // Run with: go run exercises/46/04-check-urls.go // or: go run exercises/46/04-check-urls.go URL URL ... package main import ( "fmt" "net/http" "os" "sync" "time" ) // result is what happened to one URL. type result struct { url string status string elapsed time.Duration err error } func check(client *http.Client, url string) result { start := time.Now() response, err := client.Get(url) if err != nil { return result{url: url, err: err, elapsed: time.Since(start)} } defer response.Body.Close() return result{url: url, status: response.Status, elapsed: time.Since(start)} } func main() { urls := os.Args[1:] if len(urls) == 0 { urls = []string{ "http://localhost:8080/api/items", "http://localhost:8080/api/items/1", "http://localhost:8080/api/items/999", "http://localhost:8080/nothing", "http://localhost:9999/", } } client := &http.Client{Timeout: 5 * time.Second} results := make([]result, len(urls)) start := time.Now() var wg sync.WaitGroup for i, url := range urls { wg.Go(func() { // Each goroutine writes only its own place in the slice. results[i] = check(client, url) }) } wg.Wait() for _, r := range results { if r.err != nil { fmt.Printf("FAILED %s\n %v\n", r.url, r.err) continue } fmt.Printf("%-16s %s (%v)\n", r.status, r.url, r.elapsed.Round(time.Millisecond)) } fmt.Println("All done in", time.Since(start).Round(time.Millisecond)) }