forked from ichizero/nrfiber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnrfiber.go
67 lines (56 loc) · 1.55 KB
/
nrfiber.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
package nrfiber
import (
"net/http"
"net/url"
"github.com/gofiber/fiber/v2"
"github.com/newrelic/go-agent/v3/newrelic"
)
// Middleware creates Fiber middleware that instruments requests.
//
// app := fiber.New()
// // Add the nrfiber middleware before other middlewares or routes:
// app.Use(nrfiber.Middleware(app))
func Middleware(app *newrelic.Application, opts ...Option) fiber.Handler {
if app == nil {
return func(c *fiber.Ctx) error { return c.Next() } // no-op
}
cfg := newConfig()
for _, opt := range opts {
opt(cfg)
}
return func(c *fiber.Ctx) error {
txn := app.StartTransaction(cfg.transactionNameFormatter(c))
defer txn.End()
txn.SetWebRequestHTTP(convertToRequest(c))
c.SetUserContext(newrelic.NewContext(c.UserContext(), txn))
err := c.Next()
if err != nil {
txn.NoticeError(err)
}
txn.SetWebResponse(nil).WriteHeader(c.Response().StatusCode())
return nil
}
}
func convertToHeader(c *fiber.Ctx) *http.Header {
rc := c.Context()
h := http.Header{}
rc.Request.Header.VisitAll(func(k, v []byte) {
h.Set(string(k), string(v))
})
return &h
}
func convertToRequest(c *fiber.Ctx) *http.Request {
rc := c.Context()
rURL, _ := url.ParseRequestURI(string(rc.RequestURI()))
return &http.Request{
Header: *convertToHeader(c),
URL: rURL,
Method: string(rc.Method()),
TLS: rc.TLSConnectionState(),
Host: string(rc.Host()),
}
}
// FromContext returns *newrelic.Transaction from *fiber.Ctx if present.
func FromContext(c *fiber.Ctx) *newrelic.Transaction {
return newrelic.FromContext(c.UserContext())
}