第一種寫法
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
func main() {
start :=time.Now()
ch :=make(chan string)
var urls = []string{"http://www.baidu.com",
"http://www.qq.com",
"http://www.58.com",
"http://www.0532888.cn",
"https://www.xin.com",
}
for _,url:=range urls[:len(urls)]{
go fetch(url,ch)
}
for range urls[:len(urls)]{
fmt.Println(<-ch)
}
fmt.Printf("%.2fs elapsed \n",time.Since(start).Seconds())
}
func fetch(url string,ch chan<- string){
start:=time.Now()
res,err:=http.Get(url)
if err!=nil{
ch <- fmt.Sprint(err)
return
}
nbytes,err:=io.Copy(ioutil.Discard,res.Body)
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)
}
第二種寫法
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
"time"
)
func main() {
var urls = []string{"http://www.baidu.com",
"https://www.qq.com",
"https://lf.58.com",
"http://www.0532888.cn",
"https://www.xin.com",
}
start := time.Now()
wg := sync.WaitGroup{}
wg.Add(len(urls))
for _, val := range urls {
go func(url string) {
start := time.Now()
res, err := http.Get(url)
if err != nil {
fmt.Println(err)
return
}
nbytes, err := io.Copy(ioutil.Discard, res.Body)
if err != nil {
fmt.Printf("while reading %s:%v\n", url, err)
return
}
fmt.Printf("%.2fs %7d %s\n", time.Since(start).Seconds(), nbytes, url)
wg.Done()
}(val)
}
wg.Wait()
fmt.Printf("%.2fs elapsed \n", time.Since(start).Seconds())
}
0.12s 156965 http://www.baidu.com
0.26s 51216 http://www.0532888.cn
0.44s 235408 http://www.qq.com
0.51s 63305 https://www.xin.com
0.55s 131536 http://www.58.com
0.55s elapsed