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))
}
}
I have the following code in Go. Go uses http-keep-alive connection. Thus, from my understanding, httpClient.Do(req)
will not create a new connection, since golang uses default persistent connections.
From my understanding HTTP persistent connection makes one request at a time, ie the second request can only be made after first response. However if multiple threads call
makeRequest()
what will happen ? WillhttpClient.Do(req)
send another request even before previous one got a response ?I assume server times-out any keep-alive connection made by client. If server were to timeout, then the next time
httpClient.Do(req)
is called, would it establish a new connection ?