This repository has been archived by the owner on Sep 15, 2022. It is now read-only.
/
tripperware.go
69 lines (62 loc) · 2.36 KB
/
tripperware.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
package http_opentracing
import (
"fmt"
"net/http"
"log"
"github.com/improbable-eng/go-httpwares"
"github.com/improbable-eng/go-httpwares/tags"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
otlog "github.com/opentracing/opentracing-go/log"
)
// Tripperware returns a piece of client-side Tripperware that forwards opentracing tokens.
func Tripperware(opts ...Option) httpwares.Tripperware {
o := evaluateOptions(opts)
return func(next http.RoundTripper) http.RoundTripper {
return httpwares.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
if o.filterOutFunc != nil && !o.filterOutFunc(req) {
return next.RoundTrip(req)
}
newReq, clientSpan := newClientSpanFromRequest(req, o.tracer)
resp, err := next.RoundTrip(newReq)
if err != nil {
ext.Error.Set(clientSpan, true)
clientSpan.LogFields(otlog.String("event", "error"), otlog.String("message", err.Error()))
} else {
ext.HTTPStatusCode.Set(clientSpan, uint16(resp.StatusCode))
if o.statusCodeErrorFunc(resp.StatusCode) {
ext.Error.Set(clientSpan, true)
}
}
clientSpan.Finish()
return resp, err
})
}
}
func newClientSpanFromRequest(req *http.Request, tracer opentracing.Tracer) (*http.Request, opentracing.Span) {
var parentSpanContext opentracing.SpanContext
if parent := opentracing.SpanFromContext(req.Context()); parent != nil {
parentSpanContext = parent.Context()
}
clientSpan := tracer.StartSpan(
operationNameFromUrl(req),
opentracing.ChildOf(parentSpanContext),
ext.SpanKindRPCClient,
httpTag,
)
ext.HTTPUrl.Set(clientSpan, req.URL.String())
ext.HTTPMethod.Set(clientSpan, req.Method)
// This makes a copy of the request, so that both headers and context are not affected.
newReq := req.WithContext(opentracing.ContextWithSpan(req.Context(), clientSpan))
if err := tracer.Inject(clientSpan.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(newReq.Header)); err != nil {
log.Printf("http_opentracing: failed serializing trace information: %v", err)
}
return newReq, clientSpan
}
func operationNameFromUrl(req *http.Request) string {
if tags := http_ctxtags.ExtractOutbound(req); tags.Has(http_ctxtags.TagForCallService) {
vals := tags.Values()
return fmt.Sprintf("%v:%s", vals[http_ctxtags.TagForCallService], req.Method)
}
return fmt.Sprintf("%s%s", req.URL.Host, req.URL.Path)
}