pkg/httputil: also track protocol versions of HTTP response in StatsTransport

This commit is contained in:
Brad Fitzpatrick 2015-12-29 13:36:50 -08:00
parent c36a3a087e
commit 4086789731
3 changed files with 23 additions and 2 deletions

View File

@ -159,6 +159,8 @@ func main() {
if *flagVerbose {
log.Printf("HTTP requests: %d\n", httpStats.Requests())
h1, h2 := httpStats.ProtoVersions()
log.Printf(" responses: %d (h1), %d (h2)\n", h1, h2)
}
}

View File

@ -69,6 +69,8 @@ func init() {
log.Printf("Client stats: %s", stats.String())
if up.transport != nil {
log.Printf(" #HTTP reqs: %d", up.transport.Requests())
h1, h2 := up.transport.ProtoVersions()
log.Printf(" responses: %d (h1), %d (h2)\n", h1, h2)
}
}
}

View File

@ -27,8 +27,9 @@ import (
// StatsTransport wraps another RoundTripper (or uses the default one) and
// counts the number of HTTP requests performed.
type StatsTransport struct {
mu sync.Mutex
reqs int
mu sync.Mutex
reqs int
h1, h2 int // responses by protocol type
// Transport optionally specifies the transport to use.
// If nil, http.DefaultTransport is used.
@ -44,6 +45,13 @@ func (t *StatsTransport) Requests() int {
return t.reqs
}
// ProtoVersions returns how many HTTP/1 and HTTP/2 responses were seen.
func (t *StatsTransport) ProtoVersions() (h1, h2 int) {
t.mu.Lock()
defer t.mu.Unlock()
return t.h1, t.h2
}
func (t *StatsTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
t.mu.Lock()
t.reqs++
@ -70,6 +78,15 @@ func (t *StatsTransport) RoundTrip(req *http.Request) (resp *http.Response, err
log.Printf("(%d) %s %s = error: %v (in %v)", n, req.Method, req.URL, err, td)
}
}
if resp != nil {
t.mu.Lock()
defer t.mu.Unlock()
if resp.ProtoMajor == 2 {
t.h2++
} else {
t.h1++
}
}
return
}