Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.04 KB | None | 0 0
  1. // Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
  2. // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
  3.  
  4. // See page 17.
  5. //!+
  6.  
  7. // Fetchall fetches URLs in parallel and reports their times and sizes.
  8. package main
  9.  
  10. import (
  11.     "fmt"
  12.     "io"
  13.     "io/ioutil"
  14.     "net/http"
  15.     "os"
  16.     "time"
  17. )
  18.  
  19. func main() {
  20.     start := time.Now()
  21.     ch := make(chan string)
  22.     for _, url := range os.Args[1:] {
  23.         go fetch(url, ch) // start a goroutine
  24.     }
  25.     for range os.Args[1:] {
  26.         fmt.Println(<-ch) // receive from channel ch
  27.     }
  28.     fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
  29. }
  30.  
  31. func fetch(url string, ch chan<- string) {
  32.     start := time.Now()
  33.     resp, err := http.Get(url)
  34.     if err != nil {
  35.         ch <- fmt.Sprint(err) // send to channel ch
  36.         return
  37.     }
  38.  
  39.     nbytes, err := io.Copy(ioutil.Discard, resp.Body)
  40.     resp.Body.Close() // don't leak resources
  41.     if err != nil {
  42.         ch <- fmt.Sprintf("while reading %s: %v", url, err)
  43.         return
  44.     }
  45.     secs := time.Since(start).Seconds()
  46.     ch <- fmt.Sprintf("%.2fs  %7d  %s", secs, nbytes, url)
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement