1 回答

TA貢獻2039條經驗 獲得超8個贊
你可以做這樣的事情。proxy.Transport用另一個實現(xiàn)來包裝http.RoundtripperRoundTrip 響應所需的時間。
我認為這通常會向您顯示“響應時間”。不是“請求時間”,因為仍然可以從響應中讀取正文,因此請求可能仍在進行中,但這應該大致顯示服務器響應請求所需的時間。
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"time"
)
func main() {
url, _ := url.Parse("https://stackoverflow.com")
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.Transport = NewTimingRoundtripper(http.DefaultTransport)
}
type TimingRoundtripper struct {
transport http.RoundTripper
}
func NewTimingRoundtripper(transport http.RoundTripper) http.RoundTripper {
return TimingRoundtripper{transport: transport}
}
func (rt TimingRoundtripper) RoundTrip(r *http.Request) (resp *http.Response, err error) {
start := time.Now()
resp, err = rt.transport.RoundTrip(r)
fmt.Println("request", r.URL, time.Since(start))
return resp, err
}
如果您想傳遞一個自定義*tls.Config(如下所示),您可以創(chuàng)建一個具有與相同參數(shù)http.DefaultTransport但具有自定義的新傳輸*tls.Config。
var myTransport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
然后像這樣初始化:
proxy.Transport = NewTimingRoundtripper(myTransport)
- 1 回答
- 0 關注
- 137 瀏覽
添加回答
舉報