并发的获取多个url中内容:
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
list := []string{"https://www.baidu.com", "https://www.baidu.com"}
for _, url := range list {
go fetch(url, ch) // start a goroutine
}
for range list {
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()
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)
}
代码解读:
时间相关可参考:https://blog.csdn.net/wschq/article/details/80114036