GO1.5实现简单的http并发请求,支持:GET、POST、HEAD、PUT
2015-08-08 10:00
856 查看
package main import ( "flag" "fmt" "io/ioutil" "net/http" "sync/atomic" "time" ) func main() { connection := flag.Int("c", 200, "-c N") timeout := flag.Int("o", 5, "-o N") timeover := flag.Int("t", 5, "-t N") printresult := flag.Bool("p", false, "-p false") method := flag.String("m", "GET", "-m GET") url := flag.String("u", "http://127.0.0.1", "-u http://127.0.0.1") flag.Parse() var Count int32 defer func() { if !*printresult { fmt.Println("成功响应:", Count) } }() T := time.Tick(time.Duration(*timeover) * time.Second) var result chan string = make(chan string, 10) t := time.Duration(*timeout) * time.Second Client := http.Client{Timeout: t} for i := 0; i < *connection; i++ { go func() { req, _ := http.NewRequest(*method, *url, nil) resp, _ := Client.Do(req) defer resp.Body.Close() if resp.StatusCode == 200 { b, _ := ioutil.ReadAll(resp.Body) result <- string(b) atomic.AddInt32(&Count, int32(1)) } }() } for { select { case x := <-result: if *printresult { fmt.Print(x) } case <-T: return } } }
相关文章推荐
- Go 语言 Channel 实现原理精要
- Go语言将支持Android
- 探究在C++程序并发时保护共享数据的问题
- Golang实现的聊天程序服务端和客户端代码分享
- Go语言入门教程之Arrays、Slices、Maps、Range操作简明总结
- GO语言异常处理机制panic和recover分析
- go语言执行windows下命令行的方法
- Go语言计算两个经度和纬度之间距离的方法
- Go语言排序与接口实例分析
- Go语言导出内容到Excel的方法
- go语言实现sqrt的方法
- Go语言MessageBox用法实例
- Go语言判断指定文件是否存在的方法
- 浅析PHP中Session可能会引起并发问题
- Oracle 数据库针对表主键列并发导致行级锁简单演示
- go语言制作的zip压缩程序
- go语言channel实现多核并行化运行的方法
- Go语言MD5加密用法实例
- GO语言类型转换和类型断言实例分析
- go语言使用scp的方法实例分析