/
httprouter.go
40 lines (33 loc) · 1.25 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
package hnyhttprouter
import (
"net/http"
"reflect"
"runtime"
"github.com/honeycombio/beeline-go/wrappers/common"
"github.com/julienschmidt/httprouter"
)
// Middleware wraps httprouter handlers. Since it wraps handlers with explicit
// parameters, it can add those values to the event it generates.
func Middleware(handle httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// get a new context with our trace from the request, and add common fields
ctx, span := common.StartSpanOrTraceFromHTTP(r)
defer span.Send()
// push the context with our trace and span on to the request
r = r.WithContext(ctx)
// replace the writer with our wrapper to catch the status code
wrappedWriter := common.NewResponseWriter(w)
// pull out any variables in the URL, add the thing we're matching, etc.
for _, param := range ps {
span.AddField("handler.vars."+param.Key, param.Value)
}
name := runtime.FuncForPC(reflect.ValueOf(handle).Pointer()).Name()
span.AddField("handler.name", name)
span.AddField("name", name)
handle(wrappedWriter.Wrapped, r, ps)
if wrappedWriter.Status == 0 {
wrappedWriter.Status = 200
}
span.AddField("response.status_code", wrappedWriter.Status)
}
}