Ver Fonte

异步、goroutine、ioutil.Discard(垃圾桶的使用)

龚成明 há 2 anos atrás
pai
commit
35904e5616
1 ficheiros alterados com 39 adições e 0 exclusões
  1. 39 0
      chapter01/06/fetchall.go

+ 39 - 0
chapter01/06/fetchall.go

@@ -0,0 +1,39 @@
+package main
+
+import (
+	"fmt"
+	"io"
+	"io/ioutil"
+	"net/http"
+	"os"
+	"time"
+)
+
+func main() {
+	start := time.Now()
+	ch := make(chan string)
+	for _, url := range os.Args[1:] {
+		go fetch(url, ch)
+	}
+	for range os.Args[1:] {
+		fmt.Println(<-ch)
+	}
+	fmt.Printf("%.2fs    elapsed\n", time.Since(start).Seconds())
+}
+
+func fetch(url string, ch chan<- string) {
+	start := time.Now()
+	resp, err := http.Get(url)
+	if err != nil {
+		ch <- fmt.Sprint(err)
+		return
+	}
+	nbytes, err := io.Copy(ioutil.Discard, resp.Body)
+	resp.Body.Close()
+	if err != nil {
+		ch <- fmt.Sprintf("while reading %s: %v", url, err)
+		return
+	}
+	secs := time.Since(start).Seconds()
+	ch <- fmt.Sprintf("%.2fs    %-7d    %s", secs, nbytes, url)
+}