fetchall.go 708 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "time"
  9. )
  10. func main() {
  11. start := time.Now()
  12. ch := make(chan string)
  13. for _, url := range os.Args[1:] {
  14. go fetch(url, ch)
  15. }
  16. for range os.Args[1:] {
  17. fmt.Println(<-ch)
  18. }
  19. fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
  20. }
  21. func fetch(url string, ch chan<- string) {
  22. start := time.Now()
  23. resp, err := http.Get(url)
  24. if err != nil {
  25. ch <- fmt.Sprint(err)
  26. return
  27. }
  28. nbytes, err := io.Copy(ioutil.Discard, resp.Body)
  29. resp.Body.Close()
  30. if err != nil {
  31. ch <- fmt.Sprintf("while reading %s: %v", url, err)
  32. return
  33. }
  34. secs := time.Since(start).Seconds()
  35. ch <- fmt.Sprintf("%.2fs %-7d %s", secs, nbytes, url)
  36. }