forked from DataDog/dd-trace-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
56 lines (49 loc) · 1.82 KB
/
http.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
// 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 http provides functions to trace the net/http package (https://golang.org/pkg/net/http).
package http // import "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http"
import (
"net/http"
"gopkg.in/DataDog/dd-trace-go.v1/contrib/internal/httputil"
)
// ServeMux is an HTTP request multiplexer that traces all the incoming requests.
type ServeMux struct {
*http.ServeMux
cfg *config
}
// NewServeMux allocates and returns an http.ServeMux augmented with the
// global tracer.
func NewServeMux(opts ...Option) *ServeMux {
cfg := new(config)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}
return &ServeMux{
ServeMux: http.NewServeMux(),
cfg: cfg,
}
}
// ServeHTTP dispatches the request to the handler
// whose pattern most closely matches the request URL.
// We only need to rewrite this function to be able to trace
// all the incoming requests to the underlying multiplexer
func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the resource associated to this request
_, route := mux.Handler(r)
resource := r.Method + " " + route
httputil.TraceAndServe(mux.ServeMux, w, r, mux.cfg.serviceName, resource, nil, mux.cfg.spanOpts...)
}
// WrapHandler wraps an http.Handler with tracing using the given service and resource.
func WrapHandler(h http.Handler, service, resource string, opts ...Option) http.Handler {
cfg := new(config)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
httputil.TraceAndServe(h, w, req, service, resource, cfg.finishOpts, cfg.spanOpts...)
})
}