如果有人仍在寻找如何做的答案,这就是我正在做的事情。
package main
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"time"
)
func httpClient() *http.Client {
client := &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: 20,
},
Timeout: 10 * time.Second,
}
return client
}
func sendRequest(client *http.Client, method string) []byte {
endpoint := "https://httpbin.org/post"
req, err := http.NewRequest(method, endpoint, bytes.NewBuffer([]byte("Post this data")))
if err != nil {
log.Fatalf("Error Occured. %+v", err)
}
response, err := client.Do(req)
if err != nil {
log.Fatalf("Error sending request to API endpoint. %+v", err)
}
// Close the connection to reuse it
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatalf("Couldn't parse response body. %+v", err)
}
return body
}
func main() {
c := httpClient()
response := sendRequest(c, http.MethodPost)
log.Println("Response Body:", string(response))
}
去游乐场: https: //play.golang.org/p/cYWdFu0r62e
总之,我正在创建一种不同的方法来创建 HTTP 客户端并将其分配给一个变量,然后使用它来发出请求。注意
defer response.Body.Close()
这将在函数执行结束时请求完成后关闭连接,您可以多次重用客户端。
如果要循环发送请求,请调用循环发送请求的函数。
如果您想更改客户端传输配置中的任何内容,例如添加代理配置,请在客户端配置中进行更改。
希望这会对某人有所帮助。