Hi guys:

my question is how to reuse underlying TCP connection when doing a lot of 
frequent short HTTP requests using golang?

I tried things from stackoverflow and other blogs including:


they say the key is to close resp.Body, here's my test code(as the answer 
from stackoverflow):

// init HTTPClient
func init() {
   httpClient = createHTTPClient()
const (
    MaxIdleConnections int = 10
    RequestTimeout int = 5
// createHTTPClient for connection re-use
func createHTTPClient() *http.Client {
   client := &http.Client{
       Transport: &http.Transport{
           MaxIdleConnsPerHost: MaxIdleConnections,
       Timeout: time.Duration(RequestTimeout) * time.Second,
    return client
func httpClientCode() {
    var endPoint string = "http://localhost:8080/doSomething";
    for i := 0; i < 3; i++ {
        req, err := http.NewRequest("POST", endPoint, bytes.NewBuffer([]byte
("Post this data")))
        if err != nil {
            log.Fatalf("Error Occured. %+v", err)
        req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
        response, err := httpClient.Do(req)
        if err != nil && response == nil {
            log.Fatalf("Error sending request to API endpoint. %+v", err)
        } else {
            io.Copy(ioutil.Discard, response.Body)

then I start a http server:  
python3 -m http.server 8080
and then i start package capture:
sudo tcpdump -i lo -s 0 -w /tmp/p1.pcap dst port 8080
then run: go run main.go, i still got 3 times of TCP handshake, even after 
i change MaxIdleConnections to 1


any thoughts?  thx

You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to