-
Notifications
You must be signed in to change notification settings - Fork 2
/
nrfiber.go
86 lines (69 loc) · 1.71 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package nrfiber
import (
"net/http"
"net/url"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
)
func transformRequestHeaders(r *fasthttp.Request) http.Header {
header := make(http.Header)
r.Header.VisitAll(func(k, v []byte) {
sk := string(k)
sv := string(v)
header.Set(sk, sv)
})
return header
}
func transformResponseHeaders(r *fasthttp.Response) http.Header {
header := make(http.Header)
r.Header.VisitAll(func(k, v []byte) {
sk := string(k)
sv := string(v)
header.Set(sk, sv)
})
return header
}
func toHTTPRequest(ctx *fasthttp.RequestCtx) *http.Request {
uri := ctx.Request.URI()
url := &url.URL{
Scheme: string(uri.Scheme()),
Path: string(uri.Path()),
Host: string(uri.Host()),
RawQuery: string(uri.QueryString()),
}
return &http.Request{
Method: string(ctx.Request.Header.Method()),
URL: url,
Proto: "HTTP/1.1",
Header: transformRequestHeaders(&ctx.Request),
Host: string(uri.Host()),
TLS: ctx.TLSConnectionState(),
}
}
// New creates a new middleware handler
func New(config ...Config) fiber.Handler {
// Set default config
cfg := ConfigDefault
// Override config if provided
if len(config) > 0 {
cfg = config[0]
}
app := cfg.NewRelicApp
return func(c *fiber.Ctx) error {
// Don't execute middleware if Next returns true
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
txn := app.StartTransaction(c.Path())
txn.SetWebRequestHTTP(toHTTPRequest(c.Context()))
c.Locals("newrelic_transaction", txn)
defer func() {
rw := txn.SetWebResponse(&ResponseWriter{
header: transformResponseHeaders(&c.Context().Response),
})
rw.WriteHeader(c.Context().Response.StatusCode())
txn.End()
}()
return c.Next()
}
}