Chinaunix首页 | 论坛 | 博客
  • 博客访问: 299387
  • 博文数量: 214
  • 博客积分: 4258
  • 博客等级: 上校
  • 技术积分: 2021
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-02 09:16
个人简介

http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net

文章分类

全部博文(214)

文章存档

2018年(16)

2015年(1)

2014年(2)

2012年(22)

2011年(173)

分类: C/C++

2018-01-31 10:10:10

并行获取多个url

点击(此处)折叠或打开

  1. // Fetchall fetches URLs in parallel and reports their times and sizes.
  2. package main

  3. import (
  4.     "fmt"
  5.     "io"
  6.     "io/ioutil"
  7.     "net/http"
  8.     "os"
  9.     "time"
  10. )

  11. func main() {
  12.     start := time.Now()
  13.     ch := make(chan string)
  14.     for _, url := range os.Args[1:] {
  15.         go fetch(url, ch) // start a goroutine
  16.     }
  17.     for range os.Args[1:] {
  18.         fmt.Println(<-ch) // receive from channel ch
  19.     }
  20.     fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
  21.     //fmt.Printf("%.2fs elapsed\n", time.Since(start).String())
  22. }

  23. func fetch(url string, ch chan<- string) {
  24.     start := time.Now()
  25.     resp, err := http.Get(url)
  26.     if err != nil {
  27.         ch <- fmt.Sprint(err) // send to channel ch
  28.         return
  29.     }

  30.     nbytes, err := io.Copy(ioutil.Discard, resp.Body)
  31.     resp.Body.Close() // don't leak resources
  32.     if err != nil {
  33.         ch <- fmt.Sprintf("while reading %s: %v", url, err)
  34.         return
  35.     }
  36.     secs := time.Since(start).Seconds()
  37.     ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
  38. }

  39. //!-
输出结果:

阅读(647) | 评论(0) | 转发(0) |
0

上一篇:获取url

下一篇:没有了

给主人留下些什么吧!~~