-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathwrap_transport.go
59 lines (52 loc) Β· 1.57 KB
/
wrap_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
package xray
import (
"context"
"net/http"
"goa.design/goa/middleware"
"goa.design/goa/middleware/xray"
)
// xrayTransport wraps an http RoundTripper to add a tracing subsegment of the
// request's context segment.
type xrayTransport struct {
wrapped http.RoundTripper
}
// WrapTransport wraps a http RoundTripper with a RoundTripper which creates
// subsegments of the segment in each request's context. The subsegments
// created this way have their namespace set to "remote". The request's ctx
// must be set and contain the current request segment as set by the xray
// middleware.
//
// Example of how to wrap http.Client's transport:
//
// httpClient := &http.Client{
// Transport: WrapTransport(http.DefaultTransport),
// }
//
func WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &xrayTransport{rt}
}
// RoundTrip wraps the original RoundTripper.RoundTrip to create xray tracing
// segments.
func (t *xrayTransport) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := req.Context()
seg := ctx.Value(xray.SegKey)
if seg == nil {
return t.wrapped.RoundTrip(req)
}
s := seg.(*xray.Segment)
sub := s.NewSubsegment(req.URL.Host)
hs := &HTTPSegment{Segment: sub}
hs.RecordRequest(req, "remote")
hs.SubmitInProgress()
defer hs.Close()
// update the context with the latest segment
ctx = middleware.WithSpan(ctx, hs.TraceID, hs.ID, hs.ParentID)
req = req.WithContext(context.WithValue(ctx, xray.SegKey, hs.Segment))
resp, err := t.wrapped.RoundTrip(req)
if err != nil {
hs.RecordError(err)
} else {
hs.RecordResponse(resp)
}
return resp, err
}