-
Notifications
You must be signed in to change notification settings - Fork 1
/
newrelic.go
53 lines (46 loc) · 1.34 KB
/
newrelic.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
package newrelic
import (
"context"
"net/http"
"github.com/newrelic/go-agent/v3/newrelic"
)
// Connection - newrelic connection params
type Connection struct {
app *newrelic.Application
}
// ConnectionConfig - config to connect to newrelic
type ConnectionConfig struct {
newrelic.Config
}
// NewConnection - connection parameters
func NewConnection(ctx context.Context, params ConnectionConfig) (*Connection, error) {
nApp, err := newrelic.NewApplication(
func(config *newrelic.Config) {
*config = params.Config
},
)
if err != nil {
return nil, err
}
return &Connection{app: nApp}, nil
}
// InstrumentNewRelic is the middleware for newrelic
func (nApp *Connection) InstrumentNewRelic(next http.HandlerFunc) http.HandlerFunc {
if nApp == nil { //NewRelic Connection is not setup
return http.HandlerFunc(next.ServeHTTP)
}
fn := func(w http.ResponseWriter, r *http.Request) {
txn := nApp.app.StartTransaction(r.Method + " " + r.URL.Path)
defer txn.End()
w = txn.SetWebResponse(w)
txn.SetWebRequestHTTP(r)
//instrument the newrelic transaction into the request context.
r = newrelic.RequestWithTransactionContext(r, txn)
next.ServeHTTP(w, r)
}
return fn
}
// FetchTransaction - returns the newrelic transaction from the context.
func FetchTransaction(ctx context.Context) *newrelic.Transaction {
return newrelic.FromContext(ctx)
}