|
| 1 | +package fibernewrelic |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/gofiber/fiber/v2" |
| 6 | + "github.com/newrelic/go-agent/v3/newrelic" |
| 7 | + "net/url" |
| 8 | +) |
| 9 | + |
| 10 | +type Config struct { |
| 11 | + // License parameter is required to initialize newrelic application |
| 12 | + License string |
| 13 | + // AppName parameter is required to initialize newrelic application, default is fiber-api |
| 14 | + AppName string |
| 15 | + // Enabled parameter passed to enable/disable newrelic |
| 16 | + Enabled bool |
| 17 | + // TransportType can be HTTP or HTTPS (case-sensitive), default is HTTP |
| 18 | + TransportType string |
| 19 | +} |
| 20 | + |
| 21 | +var ConfigDefault = Config{ |
| 22 | + License: "", |
| 23 | + AppName: "fiber-api", |
| 24 | + Enabled: false, |
| 25 | + TransportType: string(newrelic.TransportHTTP), |
| 26 | +} |
| 27 | + |
| 28 | +func New(cfg Config) fiber.Handler { |
| 29 | + if cfg.TransportType != "HTTP" && cfg.TransportType != "HTTPS" { |
| 30 | + cfg.TransportType = ConfigDefault.TransportType |
| 31 | + } |
| 32 | + |
| 33 | + if cfg.AppName == "" { |
| 34 | + cfg.AppName = ConfigDefault.AppName |
| 35 | + } |
| 36 | + |
| 37 | + if cfg.License == "" { |
| 38 | + panic(fmt.Errorf("unable to create New Relic Application -> License can not be empty")) |
| 39 | + } |
| 40 | + |
| 41 | + app, err := newrelic.NewApplication( |
| 42 | + newrelic.ConfigAppName(cfg.AppName), |
| 43 | + newrelic.ConfigLicense(cfg.License), |
| 44 | + newrelic.ConfigEnabled(cfg.Enabled), |
| 45 | + ) |
| 46 | + |
| 47 | + if err != nil { |
| 48 | + panic(fmt.Errorf("unable to create New Relic Application -> %w", err)) |
| 49 | + } |
| 50 | + |
| 51 | + return func(c *fiber.Ctx) error { |
| 52 | + txn := app.StartTransaction(c.Method() + " " + c.Path()) |
| 53 | + originalURL, err := url.Parse(c.OriginalURL()) |
| 54 | + if err != nil { |
| 55 | + return c.Next() |
| 56 | + } |
| 57 | + |
| 58 | + txn.SetWebRequest(newrelic.WebRequest{ |
| 59 | + URL: originalURL, |
| 60 | + Method: c.Method(), |
| 61 | + Transport: newrelic.TransportType(cfg.TransportType), |
| 62 | + Host: c.Hostname(), |
| 63 | + }) |
| 64 | + |
| 65 | + err = c.Next() |
| 66 | + if err != nil { |
| 67 | + txn.NoticeError(err) |
| 68 | + } |
| 69 | + |
| 70 | + defer txn.SetWebResponse(nil).WriteHeader(c.Response().StatusCode()) |
| 71 | + defer txn.End() |
| 72 | + |
| 73 | + return err |
| 74 | + } |
| 75 | +} |
0 commit comments