forked from elastic/apm-agent-go
/
handler.go
84 lines (75 loc) · 2.08 KB
/
handler.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
79
80
81
82
83
84
package apmhttprouter
import (
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/elastic/apm-agent-go"
"github.com/elastic/apm-agent-go/module/apmhttp"
)
// Wrap wraps h such that it will report requests as transactions
// to Elastic APM, using route in the transaction name.
//
// By default, the returned Handle will use elasticapm.DefaultTracer.
// Use WithTracer to specify an alternative tracer.
//
// By default, the returned Handle will recover panics, reporting
// them to the configured tracer. To override this behaviour, use
// WithRecovery.
func Wrap(h httprouter.Handle, route string, o ...Option) httprouter.Handle {
opts := options{
tracer: elasticapm.DefaultTracer,
}
for _, o := range o {
o(&opts)
}
if opts.recovery == nil {
opts.recovery = apmhttp.NewTraceRecovery(opts.tracer)
}
return func(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
if !opts.tracer.Active() {
h(w, req, p)
return
}
tx := opts.tracer.StartTransaction(req.Method+" "+route, "request")
ctx := elasticapm.ContextWithTransaction(req.Context(), tx)
req = apmhttp.RequestWithContext(ctx, req)
defer tx.End()
finished := false
body := opts.tracer.CaptureHTTPRequestBody(req)
w, resp := apmhttp.WrapResponseWriter(w)
defer func() {
if v := recover(); v != nil {
opts.recovery(w, req, body, tx, v)
finished = true
}
apmhttp.SetTransactionContext(tx, req, resp, body, finished)
}()
h(w, req, p)
finished = true
}
}
type options struct {
tracer *elasticapm.Tracer
recovery apmhttp.RecoveryFunc
}
// Option sets options for tracing.
type Option func(*options)
// WithTracer returns an Option which sets t as the tracer
// to use for tracing server requests.
func WithTracer(t *elasticapm.Tracer) Option {
if t == nil {
panic("t == nil")
}
return func(o *options) {
o.tracer = t
}
}
// WithRecovery returns an Option which sets r as the recovery
// function to use for tracing server requests.
func WithRecovery(r apmhttp.RecoveryFunc) Option {
if r == nil {
panic("r == nil")
}
return func(o *options) {
o.recovery = r
}
}