forked from DataDog/dd-trace-go
/
restful.go
76 lines (64 loc) · 2.68 KB
/
restful.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
71
72
73
74
75
76
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
// Package restful provides functions to trace the emicklei/go-restful package (https://github.com/emicklei/go-restful).
package restful
import (
"math"
"strconv"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
"github.com/emicklei/go-restful"
)
// FilterFunc returns a restful.FilterFunction which will automatically trace incoming request.
func FilterFunc(configOpts ...Option) restful.FilterFunction {
cfg := newConfig()
for _, opt := range configOpts {
opt(cfg)
}
log.Debug("contrib/emicklei/go-restful: Creating tracing filter: %#v", cfg)
return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
opts := []ddtrace.StartSpanOption{
tracer.ServiceName(cfg.serviceName),
tracer.ResourceName(req.SelectedRoutePath()),
tracer.SpanType(ext.SpanTypeWeb),
tracer.Tag(ext.HTTPMethod, req.Request.Method),
tracer.Tag(ext.HTTPURL, req.Request.URL.Path),
}
if !math.IsNaN(cfg.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, cfg.analyticsRate))
}
if spanctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(req.Request.Header)); err == nil {
opts = append(opts, tracer.ChildOf(spanctx))
}
span, ctx := tracer.StartSpanFromContext(req.Request.Context(), "http.request", opts...)
defer span.Finish()
// pass the span through the request context
req.Request = req.Request.WithContext(ctx)
chain.ProcessFilter(req, resp)
span.SetTag(ext.HTTPCode, strconv.Itoa(resp.StatusCode()))
span.SetTag(ext.Error, resp.Error())
}
}
// Filter is deprecated. Please use FilterFunc.
func Filter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
opts := []ddtrace.StartSpanOption{
tracer.ResourceName(req.SelectedRoutePath()),
tracer.SpanType(ext.SpanTypeWeb),
tracer.Tag(ext.HTTPMethod, req.Request.Method),
tracer.Tag(ext.HTTPURL, req.Request.URL.Path),
}
if spanctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(req.Request.Header)); err == nil {
opts = append(opts, tracer.ChildOf(spanctx))
}
span, ctx := tracer.StartSpanFromContext(req.Request.Context(), "http.request", opts...)
defer span.Finish()
// pass the span through the request context
req.Request = req.Request.WithContext(ctx)
chain.ProcessFilter(req, resp)
span.SetTag(ext.HTTPCode, strconv.Itoa(resp.StatusCode()))
span.SetTag(ext.Error, resp.Error())
}