HTTP 重用 go HTTP connection reused
In order to let the client reuse the underlying connection we just need to read the body entirely and close it before we issue a new HTTP request.
package main
import (
"context"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httptrace"
)
func main() {
// client trace to log whether the request's underlying tcp connection was re-used
clientTrace := &httptrace.ClientTrace{
GotConn: func(info httptrace.GotConnInfo) { log.Printf("conn was reused: %t", info.Reused) },
}
traceCtx := httptrace.WithClientTrace(context.Background(), clientTrace)
// 1st request
req, err := http.NewRequestWithContext(traceCtx, http.MethodGet, "http://example.com", nil)
if err != nil {
log.Fatal(err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
log.Fatal(err)
}
res.Body.Close()
// 2nd request
req, err = http.NewRequestWithContext(traceCtx, http.MethodGet, "http://example.com", nil)
if err != nil {
log.Fatal(err)
}
_, err = http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
}
go http 参数设置示例
newClient := &http.Client{
Timeout: time.Minute * 1, //设置超时时间
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second, //限制建立TCP连接的时间
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second, //限制 TLS握手的时间
ResponseHeaderTimeout: 10 * time.Second, //限制读取response header的时间,默认 timeout + 5*time.Second
ExpectContinueTimeout: 1 * time.Second, //限制client在发送包含 Expect: 100-continue的header到收到继续发送body的response之间的时间等待。
MaxIdleConns: 2, //所有host的连接池最大连接数量,默认无穷大
MaxIdleConnsPerHost: 1, //每个host的连接池最大空闲连接数,默认2
MaxConnsPerHost: 1, //每个host的最大连接数量
IdleConnTimeout: 3 * time.Minute, //how long an idle connection is kept in the connection pool.
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
本文链接地址:https://const.net.cn/724.html