forked from DataDog/dd-trace-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chi.go
78 lines (68 loc) · 2.62 KB
/
chi.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
77
78
// 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 chi provides tracing functions for tracing the go-chi/chi package (https://github.com/go-chi/chi).
package chi // import "gopkg.in/flocasts/dd-trace-go.v1/contrib/go-chi/chi"
import (
"fmt"
"math"
"net/http"
"strconv"
"gopkg.in/flocasts/dd-trace-go.v1/ddtrace"
"gopkg.in/flocasts/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/flocasts/dd-trace-go.v1/ddtrace/tracer"
"gopkg.in/flocasts/dd-trace-go.v1/internal/log"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
// Middleware returns middleware that will trace incoming requests.
func Middleware(opts ...Option) func(next http.Handler) http.Handler {
cfg := new(config)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}
log.Debug("contrib/go-chi/chi: Configuring Middleware: %#v", cfg)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
opts := []ddtrace.StartSpanOption{
tracer.SpanType(ext.SpanTypeWeb),
tracer.ServiceName(cfg.serviceName),
tracer.Tag(ext.HTTPMethod, r.Method),
tracer.Tag(ext.HTTPURL, r.URL.Path),
tracer.Measured(),
}
if !math.IsNaN(cfg.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, cfg.analyticsRate))
}
if spanctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(r.Header)); err == nil {
opts = append(opts, tracer.ChildOf(spanctx))
}
opts = append(opts, cfg.spanOpts...)
span, ctx := tracer.StartSpanFromContext(r.Context(), "http.request", opts...)
defer span.Finish()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
// pass the span through the request context and serve the request to the next middleware
next.ServeHTTP(ww, r.WithContext(ctx))
// set the resource name as we get it only once the handler is executed
resourceName := chi.RouteContext(r.Context()).RoutePattern()
if resourceName == "" {
resourceName = "unknown"
}
resourceName = r.Method + " " + resourceName
span.SetTag(ext.ResourceName, resourceName)
// set the status code
status := ww.Status()
// 0 status means one has not yet been sent in which case net/http library will write StatusOK
if ww.Status() == 0 {
status = http.StatusOK
}
span.SetTag(ext.HTTPCode, strconv.Itoa(status))
if cfg.isStatusError(status) {
// mark 5xx server error
span.SetTag(ext.Error, fmt.Errorf("%d: %s", status, http.StatusText(status)))
}
})
}
}