```package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
urls := loadUrls("urls.txt")
for _, url := range urls {
go fetch(url, ch)
}
for range urls {
fmt.Println(<-ch)
}
fmt.Printf("%.3fs elapsed\n", time.Since(start).Seconds())
}
func loadUrls(filename string) []string {
f, err := os.Open("urls.txt")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
input := bufio.NewScanner(f)
urllist := make([]string, 0, 16)
for input.Scan() {
urllist = append(urllist, "http://"+input.Text())
}
f.Close()
return urllist
}
func fetch(url string, ch chan<- string) {
t := time.NewTimer(10 * time.Second)
select {
case <-t.C:
ch <- fmt.Sprint("time out:", url)
default:
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("%.3fs %8d %s", secs, nbytes, url)
}
}
```
有疑问加站长微信联系(非本文作者)