自己写个Golang发送Get和Post请求,也可以当个建议并发测试脚本

package main

import (
	"bytes"
	"fmt"
	//"time"
	"os"
	"sync"
	"runtime"
	//"unsafe"
	"net/http"
	"io/ioutil"
	"log"
	"strings"
	"net/url"

	"encoding/json"
	"strconv"
	//"net/url"
	//"reflect"
	simplejson "github.com/bitly/go-simplejson"
)

var ms runtime.MemStats 
var wg sync.WaitGroup
type Point struct{
	x int
	y int
}
func httpHandle(method, urlVal string, data *bytes.Reader) string{
	client := &http.Client{}
	var req *http.Request
 
	if data.Len() == 0 {
		urlArr := strings.Split(urlVal,"?")
		if len(urlArr)  == 2 {
			urlVal = urlArr[0] + "?" + getParseParam(urlArr[1])
		}
		req, _ = http.NewRequest(method, urlVal, nil)
	}else {
		req, _ = http.NewRequest(method, urlVal, data)
	}
 
	//添加cookie,key为X-Xsrftoken,value为df41ba54db5011e89861002324e63af81
    //可以添加多个cookie
	//cookie1 := &http.Cookie{Name: "X-Xsrftoken",Value: "df41ba54db5011e89861002324e63af81", HttpOnly: true}
	//req.AddCookie(cookie1)
 
    //添加header
	req.Header.Add("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2VmJXR1BMcmEyIiwiZXhwIjoxNTc0ODYxMDUwfQ.FK4WBoY4odtbnXjOR6yHMfOgfPkmi-OR0m01WckJj4g")
	req.Header.Add("content-type", "application/json")
 
	resp, err := client.Do(req)
 
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := ioutil.ReadAll(resp.Body)
	return string(b)
}
//将get请求的参数进行转义
func getParseParam(param string) string  {
	return url.PathEscape(param)
}

func Parse(i interface{}) interface{} {  
    switch i.(type) {  
    case string:  
        return i.(string)
    case int:  
       return i.(int)
    default:  
        return "err"
    }  
    return nil  
}  

//根据系统自身CPU数设置执行此代码所用CPU核数
func setMaxProcs(){
	runtime.GOMAXPROCS( runtime.NumCPU() )
}

type PostData struct{
	source string
	developer_user_id string
	transaction_id string
	good_id int
	series_id int
	brand_id int
	content string
	mobile string
	attachments string
}
func main(){

	setMaxProcs()
	//arr := make( []Point, 0 )
	//ch := make(chan int)
	//defer close(ch)

	count := 1
	success := 0
	fail := 0
	for count <= 200{
		wg.Add(1)//设置等待线程数,避免协程未执行完主协程关闭

		postData := make(map[string]interface{})
		postData["source"] = "aiyihang"
		postData["developer_user_id"] = "666"
		postData["transaction_id"] = "AB20Adad5fs34ad5sasad66999" + strconv.Itoa(count)
		postData["good_id"] = "2"
		postData["series_id"] = "16"
		postData["brand_id"] = "1"
		postData["content"] = "我的大众轮胎在车速80的时候显示胎压不足"
		postData["mobile"] = "13188888888"
		postData["attachments"] = "https://img.qcds.com/weixin/img/[email protected]|https://img.qcds.com/weixin/img/top/index_banner.jpg"
		
		byteDates, err := json.Marshal(postData)
		if err != nil {
			fmt.Println(err.Error() )
			return
		}
		reader := bytes.NewReader(byteDates)

		go func(data *bytes.Reader){
			defer wg.Done()
			body := httpHandle("POST", "http://www.test.api.com/post", data)
			ret, err := simplejson.NewJson([]byte(body))
			if err != nil{
				fmt.Println(err)
			}
			code, err := ret.Get("code").Int()
			fmt.Println(code)
			if(code == 0){
				success++
			}else{
				fail++
			}
		}(reader)
		count++
	}
	wg.Wait()
	//内存申请和分配的统计信息
	runtime.ReadMemStats(&ms)
	fmt.Println(ms.TotalAlloc)

	fmt.Println("success", success)
	fmt.Println("fail", fail)
	os.Exit(1)
}
发布了200 篇原创文章 · 获赞 26 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/103281283