mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 22:52:05 +00:00
good good study, day day up!
This commit is contained in:
49
vendor/gopl.io/ch1/fetchall/main.go
generated
vendored
Normal file
49
vendor/gopl.io/ch1/fetchall/main.go
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 17.
|
||||
//!+
|
||||
|
||||
// Fetchall fetches URLs in parallel and reports their times and sizes.
|
||||
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) // start a goroutine
|
||||
}
|
||||
for range os.Args[1:] {
|
||||
fmt.Println(<-ch) // receive from channel 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) // send to channel ch
|
||||
return
|
||||
}
|
||||
|
||||
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
|
||||
resp.Body.Close() // don't leak resources
|
||||
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)
|
||||
}
|
||||
|
||||
//!-
|
Reference in New Issue
Block a user