forked from honeycombio/beeline-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
goji.go
64 lines (58 loc) · 1.99 KB
/
goji.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
package hnygoji
import (
"net/http"
"reflect"
"runtime"
"strings"
"github.com/honeycombio/beeline-go/wrappers/common"
"goji.io/middleware"
"goji.io/pat"
)
// Middleware is specifically to use with goji's router.Use() function for
// inserting middleware
func Middleware(handler http.Handler) http.Handler {
wrappedHandler := func(w http.ResponseWriter, r *http.Request) {
// 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)
// get bits about the handler
handler := middleware.Handler(ctx)
if handler == nil {
span.AddField("handler.name", "http.NotFound")
handler = http.NotFoundHandler()
} else {
hType := reflect.TypeOf(handler)
span.AddField("handler.type", hType.String())
name := runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
span.AddField("handler.name", name)
span.AddField("name", name)
}
// find any matched patterns
pm := middleware.Pattern(ctx)
if pm != nil {
// TODO put a regex on `p.String()` to pull out any `:foo` and then
// use those instead of trying to pull them out of the pattern some
// other way
if p, ok := pm.(*pat.Pattern); ok {
span.AddField("goji.pat", p.String())
span.AddField("goji.methods", p.HTTPMethods())
span.AddField("goji.path_prefix", p.PathPrefix())
patvar := strings.TrimPrefix(p.String(), p.PathPrefix()+":")
span.AddField("goji.pat."+patvar, pat.Param(r, patvar))
} else {
span.AddField("pat", "NOT pat.Pattern")
}
}
// TODO get all the parameters and their values
handler.ServeHTTP(wrappedWriter.Wrapped, r)
if wrappedWriter.Status == 0 {
wrappedWriter.Status = 200
}
span.AddField("response.status_code", wrappedWriter.Status)
}
return http.HandlerFunc(wrappedHandler)
}