main.go 1012 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "os"
  6. "github.com/gin-gonic/gin"
  7. "github.com/newrelic/go-agent"
  8. )
  9. const (
  10. // NewRelicTxnKey is the key used to retrieve the NewRelic Transaction from the context
  11. NewRelicTxnKey = "NewRelicTxnKey"
  12. )
  13. // NewRelicMonitoring is a middleware that starts a newrelic transaction, stores it in the context, then calls the next handler
  14. func NewRelicMonitoring(app newrelic.Application) gin.HandlerFunc {
  15. return func(ctx *gin.Context) {
  16. txn := app.StartTransaction(ctx.Request.URL.Path, ctx.Writer, ctx.Request)
  17. defer txn.End()
  18. ctx.Set(NewRelicTxnKey, txn)
  19. ctx.Next()
  20. }
  21. }
  22. func main() {
  23. router := gin.Default()
  24. cfg := newrelic.NewConfig(os.Getenv("APP_NAME"), os.Getenv("NEW_RELIC_API_KEY"))
  25. app, err := newrelic.NewApplication(cfg)
  26. if err != nil {
  27. log.Printf("failed to make new_relic app: %v", err)
  28. } else {
  29. router.Use(NewRelicMonitoring(app))
  30. }
  31. router.GET("/", func(c *gin.Context) {
  32. c.String(http.StatusOK, "Hello World!\n")
  33. })
  34. router.Run()
  35. }