git.colasdn.top/newrelic/go-agent@v3.26.0+incompatible/_integrations/nrecho/example/main.go (about) 1 // Copyright 2020 New Relic Corporation. All rights reserved. 2 // SPDX-License-Identifier: Apache-2.0 3 4 package main 5 6 import ( 7 "fmt" 8 "net/http" 9 "os" 10 11 "github.com/labstack/echo" 12 "github.com/labstack/echo/middleware" 13 "github.com/newrelic/go-agent" 14 "github.com/newrelic/go-agent/_integrations/nrecho" 15 ) 16 17 func mustGetEnv(key string) string { 18 if val := os.Getenv(key); "" != val { 19 return val 20 } 21 panic(fmt.Sprintf("environment variable %s unset", key)) 22 } 23 24 func getUser(c echo.Context) error { 25 id := c.Param("id") 26 27 if txn := nrecho.FromContext(c); nil != txn { 28 txn.AddAttribute("userId", id) 29 } 30 31 return c.String(http.StatusOK, id) 32 } 33 34 func main() { 35 cfg := newrelic.NewConfig("Echo App", mustGetEnv("NEW_RELIC_LICENSE_KEY")) 36 cfg.Logger = newrelic.NewDebugLogger(os.Stdout) 37 app, err := newrelic.NewApplication(cfg) 38 if nil != err { 39 fmt.Println(err) 40 os.Exit(1) 41 } 42 43 // Echo instance 44 e := echo.New() 45 46 // The New Relic Middleware should be the first middleware registered 47 e.Use(nrecho.Middleware(app)) 48 49 // Routes 50 e.GET("/home", func(c echo.Context) error { 51 return c.String(http.StatusOK, "Hello, World!") 52 }) 53 54 // Groups 55 g := e.Group("/user") 56 g.Use(middleware.Gzip()) 57 g.GET("/:id", getUser) 58 59 // Start server 60 e.Start(":8000") 61 }