github.com/lulzWill/go-agent@v2.1.2+incompatible/_integrations/nrgorilla/v1/nrgorilla.go (about) 1 // Package nrgorilla introduces to support for the gorilla/mux framework. See 2 // examples/_gorilla/main.go for an example. 3 package nrgorilla 4 5 import ( 6 "net/http" 7 8 "github.com/gorilla/mux" 9 newrelic "github.com/lulzWill/go-agent" 10 "github.com/lulzWill/go-agent/internal" 11 ) 12 13 func init() { internal.TrackUsage("integration", "framework", "gorilla", "v1") } 14 15 type instrumentedHandler struct { 16 name string 17 app newrelic.Application 18 orig http.Handler 19 } 20 21 func (h instrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 22 txn := h.app.StartTransaction(h.name, w, r) 23 defer txn.End() 24 25 h.orig.ServeHTTP(txn, r) 26 } 27 28 func instrumentRoute(h http.Handler, app newrelic.Application, name string) http.Handler { 29 if _, ok := h.(instrumentedHandler); ok { 30 return h 31 } 32 return instrumentedHandler{ 33 name: name, 34 orig: h, 35 app: app, 36 } 37 } 38 39 func routeName(route *mux.Route) string { 40 if nil == route { 41 return "" 42 } 43 if n := route.GetName(); n != "" { 44 return n 45 } 46 if n, _ := route.GetPathTemplate(); n != "" { 47 return n 48 } 49 n, _ := route.GetHostTemplate() 50 return n 51 } 52 53 // InstrumentRoutes adds instrumentation to a router. This must be used after 54 // the routes have been added to the router. 55 func InstrumentRoutes(r *mux.Router, app newrelic.Application) *mux.Router { 56 r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { 57 h := instrumentRoute(route.GetHandler(), app, routeName(route)) 58 route.Handler(h) 59 return nil 60 }) 61 if nil != r.NotFoundHandler { 62 r.NotFoundHandler = instrumentRoute(r.NotFoundHandler, app, "NotFoundHandler") 63 } 64 return r 65 }