Reusing http connections in Golang

前端 未结 9 773
时光取名叫无心
时光取名叫无心 2020-12-02 04:27

I\'m currently struggling to find a way to reuse connections when making HTTP posts in Golang.

I\'ve created a transport and client like so:

// Crea         


        
相关标签:
9条回答
  • 2020-12-02 05:17

    Edit: This is more of a note for people that construct a Transport and Client for every request.

    Edit2: Changed link to godoc.

    Transport is the struct that holds connections for re-use; see https://godoc.org/net/http#Transport ("By default, Transport caches connections for future re-use.")

    So if you create a new Transport for each request, it will create new connections each time. In this case the solution is to share the one Transport instance between clients.

    0 讨论(0)
  • 2020-12-02 05:18

    Another approach to init() is to use a singleton method to get the http client. By using sync.Once you can be sure that only one instance will be used on all your requests.

    var (
        once              sync.Once
        netClient         *http.Client
    )
    
    func newNetClient() *http.Client {
        once.Do(func() {
            var netTransport = &http.Transport{
                Dial: (&net.Dialer{
                    Timeout: 2 * time.Second,
                }).Dial,
                TLSHandshakeTimeout: 2 * time.Second,
            }
            netClient = &http.Client{
                Timeout:   time.Second * 2,
                Transport: netTransport,
            }
        })
    
        return netClient
    }
    
    func yourFunc(){
        URL := "local.dev"
        req, err := http.NewRequest("POST", URL, nil)
        response, err := newNetClient().Do(req)
        // ...
    }
    
    
    0 讨论(0)
  • 2020-12-02 05:24

    Ensure that you read until the response is complete AND call Close().

    e.g.

    res, _ := client.Do(req)
    io.Copy(ioutil.Discard, res.Body)
    res.Body.Close()
    

    Again... To ensure http.Client connection reuse be sure to:

    • Read until Response is complete (i.e. ioutil.ReadAll(resp.Body))
    • Call Body.Close()
    0 讨论(0)
提交回复
热议问题