Reusing http connections in Golang

前端 未结 9 857
时光取名叫无心
时光取名叫无心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 05:02

    If anyone is still finding answers on how to do it, this is how I am doing it.

    package main
    
    import (
        "bytes"
        "io/ioutil"
        "log"
        "net/http"
        "time"
    )
    
    var httpClient *http.Client
    
    const (
        MaxIdleConnections int = 20
        RequestTimeout     int = 5
    )
    
    func init() {
        httpClient = createHTTPClient()
    }
    
    // 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 main() {
        endPoint := "https://localhost:8080/doSomething"
    
        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)
        }
    
        // Close the connection to reuse it
        defer response.Body.Close()
    
        // Let's check if the work actually is done
        // We have seen inconsistencies even when we get 200 OK response
        body, err := ioutil.ReadAll(response.Body)
        if err != nil {
            log.Fatalf("Couldn't parse response body. %+v", err)
        }
    
        log.Println("Response Body:", string(body))    
    }
    

    Go Playground: http://play.golang.org/p/oliqHLmzSX

    In summary, I am creating a different method to create a HTTP client and assigning it to global variable and then using it to make requests. Note the

    defer response.Body.Close() 
    

    This will close the connection and set it ready for reuse again.

    Hope this will help someone.

提交回复
热议问题