/
negroni.go
66 lines (56 loc) · 1.92 KB
/
negroni.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
// 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 negroni provides helper functions for tracing the urfave/negroni package (https://github.com/urfave/negroni).
package negroni
import (
"fmt"
"math"
"net/http"
"github.com/urfave/negroni"
httptrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http"
"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"
)
// DatadogMiddleware returns middleware that will trace incoming requests.
type DatadogMiddleware struct {
cfg *config
}
func (m *DatadogMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
opts := append(m.cfg.spanOpts, tracer.Measured())
if !math.IsNaN(m.cfg.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, m.cfg.analyticsRate))
}
span, ctx := httptrace.StartRequestSpan(r, m.cfg.serviceName, m.cfg.resourceNamer(r), false, opts...)
defer func() {
// check if the responseWriter is of type negroni.ResponseWriter
var (
status int
opts []tracer.FinishOption
)
responseWriter, ok := w.(negroni.ResponseWriter)
if ok {
status = responseWriter.Status()
if m.cfg.isStatusError(status) {
opts = []tracer.FinishOption{tracer.WithError(fmt.Errorf("%d: %s", status, http.StatusText(status)))}
}
}
httptrace.FinishRequestSpan(span, status, opts...)
}()
next(w, r.WithContext(ctx))
}
// Middleware create the negroni middleware that will trace incoming requests
func Middleware(opts ...Option) *DatadogMiddleware {
cfg := new(config)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}
log.Debug("contrib/urgave/negroni: Configuring Middleware: %#v", cfg)
m := DatadogMiddleware{
cfg: cfg,
}
return &m
}