-
Notifications
You must be signed in to change notification settings - Fork 0
/
nrecho.go
91 lines (75 loc) · 2.44 KB
/
nrecho.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
85
86
87
88
89
90
91
// Package nrecho instruments https://github.com/labstack/echo applications.
//
// Use this package to instrument inbound requests handled by an echo.Echo
// instance.
//
// e := echo.New()
// // Add the nrecho middleware before other middlewares or routes:
// e.Use(nrecho.Middleware(app))
//
// Example: https://github.com/newrelic/go-agent/tree/master/_integrations/nrecho/example/main.go
//
// (RB): This new version was made for compatibility with v4
package nrecho
import (
"net/http"
"reflect"
"github.com/labstack/echo/v4"
newrelic "github.com/newrelic/go-agent"
)
// func init() { internal.TrackUsage("integration", "framework", "echo") }
// FromContext returns the Transaction from the context if present, and nil
// otherwise.
func FromContext(c echo.Context) newrelic.Transaction {
return newrelic.FromContext(c.Request().Context())
}
func handlerPointer(handler echo.HandlerFunc) uintptr {
return reflect.ValueOf(handler).Pointer()
}
func transactionName(c echo.Context) string {
ptr := handlerPointer(c.Handler())
if ptr == handlerPointer(echo.NotFoundHandler) {
return "NotFoundHandler"
}
if ptr == handlerPointer(echo.MethodNotAllowedHandler) {
return "MethodNotAllowedHandler"
}
return c.Path()
}
// Middleware creates Echo middleware that instruments requests.
//
// e := echo.New()
// // Add the nrecho middleware before other middlewares or routes:
// e.Use(nrecho.Middleware(app))
//
func Middleware(app newrelic.Application) func(echo.HandlerFunc) echo.HandlerFunc {
if nil == app {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return next
}
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
rw := c.Response().Writer
txn := app.StartTransaction(transactionName(c), rw, c.Request())
defer txn.End()
c.Response().Writer = txn
// Add txn to c.Request().Context()
c.SetRequest(c.Request().WithContext(newrelic.NewContext(c.Request().Context(), txn)))
err = next(c)
// Record the response code. The response headers are not captured
// in this case because they are set after this middleware returns.
// Designed to mimic the logic in echo.DefaultHTTPErrorHandler.
if nil != err && !c.Response().Committed {
txn.SetWebResponse(nil)
c.Response().Writer = rw
if httperr, ok := err.(*echo.HTTPError); ok {
txn.WriteHeader(httperr.Code)
} else {
txn.WriteHeader(http.StatusInternalServerError)
}
}
return
}
}
}