-
Notifications
You must be signed in to change notification settings - Fork 32
/
transport.go
70 lines (57 loc) · 1.34 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package httpstats
import (
"net/http"
"time"
"github.com/segmentio/stats"
)
// NewTransport wraps t to produce metrics on the default engine for every request
// sent and every response received.
func NewTransport(t http.RoundTripper) http.RoundTripper {
return NewTransportWith(stats.DefaultEngine, t)
}
// NewTransportWith wraps t to produce metrics on eng for every request sent and
// every response received.
func NewTransportWith(eng *stats.Engine, t http.RoundTripper) http.RoundTripper {
return &transport{
transport: t,
eng: eng,
}
}
type transport struct {
transport http.RoundTripper
eng *stats.Engine
}
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) {
start := time.Now()
rtrip := t.transport
if rtrip == nil {
rtrip = http.DefaultTransport
}
if req.Body == nil {
req.Body = &nullBody{}
}
m := &metrics{}
req.Body = &requestBody{
eng: t.eng,
req: req,
metrics: m,
body: req.Body,
op: "write",
}
res, err = rtrip.RoundTrip(req)
req.Body.Close() // safe guard, the transport should have done it already
if err != nil {
m.observeError(time.Now().Sub(start))
t.eng.ReportAt(start, m)
} else {
res.Body = &responseBody{
eng: t.eng,
res: res,
metrics: m,
body: res.Body,
op: "read",
start: start,
}
}
return
}