Reusing http connections in Golang

前端 未结 9 771
时光取名叫无心
时光取名叫无心 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: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)
        // ...
    }
    
    

提交回复
热议问题