I have a web reverse proxy based on http/net. I'm using NewSingleHostReverseProxy function. How can I measure response times of target web server ?
CodePudding user response:
You could do something like this. Wrap the proxy.Transport with another http.Roundtripper implementation that times how long it takes RoundTrip to respond.
I think this will generally show you "response time". Not "request time", since the body can still be read from the response, so the request could still be ongoing, but this should show you roughly how long it takes the server to respond to the request.
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
}
If you would like to pass a custom *tls.Config (as asked below) you can create a new transport with the same parameters as the http.DefaultTransport but with a custom *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},
}
And then initialize like so:
proxy.Transport = NewTimingRoundtripper(myTransport)
