码迷,mamicode.com
首页 > Web开发 > 详细

GO1.5实现简单的http并发请求

时间:2015-08-08 10:32:51      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:golang   go语言   并发   go   

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
		}
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

GO1.5实现简单的http并发请求

标签:golang   go语言   并发   go   

原文地址:http://blog.csdn.net/fyxichen/article/details/47355577

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!