package main import ( "fmt" "io" "net/http" "net/url" ) // 全局公用链接,请求频率比较频繁 //var ( // client = http.Client{ // Transport: &http.Transport{DisableKeepAlives: false}, // } //) func main() { apiUrl := "http://127.0.0.1:9090/query" apiParseUrl, err := url.Parse(apiUrl) //url不带参数传入,返回一个结构体 if err != nil { fmt.Println("url parse err:", err) } data := url.Values{} data.Set("name", "王奥") data.Set("age", "18") //set url中带参的数据 paramStr := data.Encode() //编码 apiParseUrl.RawQuery = paramStr //赋值到url的结构体中,组成完整的url编码对象 //自定义client 禁用keepalive 适用于请求频率不频繁,每次请求生成一个短链接,之后释放 tr := http.Transport{DisableKeepAlives: true} //短链接 client := http.Client{ Transport: &tr, } //生成请求对象 req, err := http.NewRequest("GET", apiParseUrl.String(), nil) if err != nil { fmt.Println("start new req err:", err) } //如果使用默认client: //http.DefaultClient.Do(req) //发送自定义请求 resp, err := client.Do(req) if err != nil { return } defer resp.Body.Close() //关闭请求体 //读取返回体 body, err := io.ReadAll(resp.Body) if err != nil { fmt.Println("read resp body err:", err) } fmt.Println("resp body:", string(body)) }