golang最简单的http client(GET方法),包括json.Unmarshal,fmt格式化输出

工程中用的测试用例代码

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type Response struct {
	Count int `json:"count"`
}
func main() {
	ipDesp:=make(map[string]string, 14)
	ipDesp["这里是ip"]="华东杭州"
	ipDesp["这里是ip"]="华东杭州"

	ipDesp["这里是ip"]="华东上海"
	ipDesp["这里是ip"]="华东上海"

	client := &http.Client{}
	for{
		t := time.Now()
		fmt.Println("----------------------------------------------------begin")
		fmt.Println(time.Now().Format(time.RFC850), t.Unix())
		fmt.Println("----------------------------------------------------")
		var count int
		var count_hd, counthb, counthn int
		for k,v:=range ipDesp{
			url := fmt.Sprintf("http://%s:8141/yourpath",k)
			request, _ := http.NewRequest("GET", url, nil)
			//fmt.Println(url)
			response, _ := client.Do(request)
			if response.StatusCode == 200 {
				body, _ := ioutil.ReadAll(response.Body)
				//fmt.Println(string(body))
				var r = Response{}
				json.Unmarshal(body,&r)
				out:=fmt.Sprintf("%8s\t%2d\t%s\t",v,r.Count,k)
				fmt.Println(out)
				count+=r.Count
				if strings.Contains(v,"华南"){
					counthn+=r.Count
				}else if strings.Contains(v,"华东"){
					count_hd+=r.Count
				}else if strings.Contains(v,"华北"){
					counthb+=r.Count
				}
			}
		}
		fmt.Println("同时在线:",count, "华东:",count_hd,"华南:",counthn,"华北:",counthb)
		fmt.Println("----------------------------------------------------end")
		time.Sleep(5*time.Second)
	}
}

如果增加超时

	client := &http.Client{
		Timeout: time.Duration(1 * time.Second),
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值