Reusing http connections in Golang

前端 未结 9 808
时光取名叫无心
时光取名叫无心 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:03

    about Body

    // It is the caller's responsibility to
    // close Body. The default HTTP client's Transport may not
    // reuse HTTP/1.x "keep-alive" TCP connections if the Body is
    // not read to completion and closed.
    

    So if you want to reuse TCP connections, you have to close Body every time after read to completion. An function ReadBody(io.ReadCloser) is suggested like this.

    package main
    
    import (
        "fmt"
        "io"
        "io/ioutil"
        "net/http"
        "time"
    )
    
    func main() {
        req, err := http.NewRequest(http.MethodGet, "https://github.com", nil)
        if err != nil {
            fmt.Println(err.Error())
            return
        }
        client := &http.Client{}
        i := 0
        for {
            resp, err := client.Do(req)
            if err != nil {
                fmt.Println(err.Error())
                return
            }
            _, _ = readBody(resp.Body)
            fmt.Println("done ", i)
            time.Sleep(5 * time.Second)
        }
    }
    
    func readBody(readCloser io.ReadCloser) ([]byte, error) {
        defer readCloser.Close()
        body, err := ioutil.ReadAll(readCloser)
        if err != nil {
            return nil, err
        }
        return body, nil
    }
    

提交回复
热议问题