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:

https://stackoverflow.com/questions/17948827/reusing-http-connections-in-golang
https://awmanoj.github.io/tech/2016/12/16/keep-alive-http-requests-in-golang/

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)
            response.Body.Close()
        }
    }
}

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

<https://lh3.googleusercontent.com/-gbXW0h7LCvQ/Wsy4Rw8BzAI/AAAAAAAAANU/1F1n5nzl9IYw6fHAp0__kUGoM6UL6f_VQCLcBGAs/s1600/google_question.jpg>


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