var (
httpClient *http.Client
)
const (
MaxIdleConnections int = 20
RequestTimeout int = 5
)
// init HTTPClient
func init() {
client := &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: MaxIdleConnections,
},
Timeout: time.Duration(RequestTimeout) * time.Second,
}
return client
}
func makeRequest() {
var endPoint string = "https://localhost:8080/doSomething"
req, err := http.NewRequest("GET", ....)
response, err := httpClient.Do(req)
if err != nil && response == nil {
log.Fatalf("Error sending request to API endpoint. %+v", err)
} else {
// 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)
}
log.Println("Response Body:", string(body))
}
}
我在Go中有以下代码。Go使用http-keep-alive连接。因此,据我所知,httpClient.Do(req)
不会创建新连接,因为golang使用默认的持久连接。
据我了解,HTTP持久连接一次只能发送一个请求,即第二个请求只能在第一个响应之后发出。但是如果多个线程调用
makeRequest()
会发生什么?httpClient.Do(req)
是否会在前一个请求得到响应之前发送另一个请求?我假设服务器会超时关闭客户端建立的任何keep-alive连接。如果服务器超时,那么下一次调用
httpClient.Do(req)
时,它会建立一个新的连接吗?