forked from DataDog/dd-trace-go
/
httprouter.go
51 lines (44 loc) · 1.66 KB
/
httprouter.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
// 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-2020 Datadog, Inc.
// Package httprouter provides functions to trace the julienschmidt/httprouter package (https://github.com/julienschmidt/httprouter).
package httprouter // import "gopkg.in/DataDog/dd-trace-go.v1/contrib/julienschmidt/httprouter"
import (
"math"
"net/http"
"strings"
"gopkg.in/DataDog/dd-trace-go.v1/contrib/internal/httputil"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"github.com/julienschmidt/httprouter"
)
// Router is a traced version of httprouter.Router.
type Router struct {
*httprouter.Router
config *routerConfig
}
// New returns a new router augmented with tracing.
func New(opts ...RouterOption) *Router {
cfg := new(routerConfig)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}
if !math.IsNaN(cfg.analyticsRate) {
cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.EventSampleRate, cfg.analyticsRate))
}
cfg.spanOpts = append(cfg.spanOpts, tracer.Measured())
return &Router{httprouter.New(), cfg}
}
// ServeHTTP implements http.Handler.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// get the resource associated to this request
route := req.URL.Path
_, ps, _ := r.Router.Lookup(req.Method, route)
for _, param := range ps {
route = strings.Replace(route, param.Value, ":"+param.Key, 1)
}
resource := req.Method + " " + route
httputil.TraceAndServe(r.Router, w, req, r.config.serviceName, resource, nil, r.config.spanOpts...)
}