forked from erkanzileli/nrfiber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nrfiber.go
98 lines (79 loc) · 2.35 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
87
88
89
90
91
92
93
94
95
96
97
98
package nrfiber
import (
"fmt"
"net/http"
"net/url"
"errors"
"github.com/gofiber/fiber/v2"
"github.com/newrelic/go-agent/v3/newrelic"
"github.com/valyala/fasthttp"
)
// FromContext returns the Transaction from the context if present, and nil
// otherwise.
func FromContext(c *fiber.Ctx) *newrelic.Transaction {
return newrelic.FromContext(c.UserContext())
}
// 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, configs ...*config) fiber.Handler {
if nil == app {
return func(c *fiber.Ctx) error {
return nil
}
}
configMap := createConfigMap(configs...)
noticeError := noticeErrorEnabled(configMap)
noticeInternalServerError := noticeInternalServerErrorEnabled(configMap)
return func(c *fiber.Ctx) error {
txn := app.StartTransaction(createTransactionName(c))
defer txn.End()
txn.SetWebRequestHTTP(createHttpRequest(c))
c.SetUserContext(newrelic.NewContext(c.UserContext(), txn))
err := c.Next()
statusCode := c.Context().Response.StatusCode()
if err != nil {
if fiberErr, ok := err.(*fiber.Error); ok {
statusCode = fiberErr.Code
}
if noticeError {
txn.NoticeError(err)
}
} else if statusCode >= fiber.StatusInternalServerError &&
noticeInternalServerError {
txn.NoticeError(errors.New(fmt.Sprintf("%d", statusCode)))
}
txn.SetWebResponse(nil).WriteHeader(statusCode)
return err
}
}
func createTransactionName(c *fiber.Ctx) string {
return fmt.Sprintf("%s %s", c.Request().Header.Method(), c.Request().URI().Path())
}
func convertRequestHeaders(fastHttpHeaders *fasthttp.RequestHeader) http.Header {
headers := make(http.Header)
fastHttpHeaders.VisitAll(func(k, v []byte) {
headers.Set(string(k), string(v))
})
return headers
}
func createHttpRequest(c *fiber.Ctx) *http.Request {
reqHeaders := convertRequestHeaders(&c.Request().Header)
reqHost := reqHeaders.Get("Host")
if reqHost == "" {
reqHost = string(c.Request().URI().Host())
}
return &http.Request{
Method: c.Method(),
URL: &url.URL{
Scheme: string(c.Request().URI().Scheme()),
Host: reqHost,
Path: string(c.Request().URI().Path()),
RawQuery: string(c.Request().URI().QueryString()),
},
Header: reqHeaders,
Host: reqHost,
}
}