github.com/lulzWill/go-agent@v2.1.2+incompatible/examples/_gin/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/gin-gonic/gin" 8 "github.com/lulzWill/go-agent" 9 "github.com/lulzWill/go-agent/_integrations/nrgin/v1" 10 ) 11 12 func makeGinEndpoint(s string) func(*gin.Context) { 13 return func(c *gin.Context) { 14 c.Writer.WriteString(s) 15 } 16 } 17 18 func v1login(c *gin.Context) { c.Writer.WriteString("v1 login") } 19 func v1submit(c *gin.Context) { c.Writer.WriteString("v1 submit") } 20 func v1read(c *gin.Context) { c.Writer.WriteString("v1 read") } 21 22 func endpoint404(c *gin.Context) { 23 c.Writer.WriteHeader(404) 24 c.Writer.WriteString("returning 404") 25 } 26 27 func endpointChangeCode(c *gin.Context) { 28 // gin.ResponseWriter buffers the response code so that it can be 29 // changed before the first write. 30 c.Writer.WriteHeader(404) 31 c.Writer.WriteHeader(200) 32 c.Writer.WriteString("actually ok!") 33 } 34 35 func endpointResponseHeaders(c *gin.Context) { 36 // Since gin.ResponseWriter buffers the response code, response headers 37 // can be set afterwards. 38 c.Writer.WriteHeader(200) 39 c.Writer.Header().Set("Content-Type", "application/json") 40 c.Writer.WriteString(`{"zip":"zap"}`) 41 } 42 43 func endpointNotFound(c *gin.Context) { 44 c.Writer.WriteString("there's no endpoint for that!") 45 } 46 47 func endpointAccessTransaction(c *gin.Context) { 48 if txn := nrgin.Transaction(c); nil != txn { 49 txn.SetName("custom-name") 50 } 51 c.Writer.WriteString("changed the name of the transaction!") 52 } 53 54 func mustGetEnv(key string) string { 55 if val := os.Getenv(key); "" != val { 56 return val 57 } 58 panic(fmt.Sprintf("environment variable %s unset", key)) 59 } 60 61 func main() { 62 cfg := newrelic.NewConfig("Gin App", mustGetEnv("NEW_RELIC_LICENSE_KEY")) 63 cfg.Logger = newrelic.NewDebugLogger(os.Stdout) 64 app, err := newrelic.NewApplication(cfg) 65 if nil != err { 66 fmt.Println(err) 67 os.Exit(1) 68 } 69 70 router := gin.Default() 71 router.Use(nrgin.Middleware(app)) 72 73 router.GET("/404", endpoint404) 74 router.GET("/change", endpointChangeCode) 75 router.GET("/headers", endpointResponseHeaders) 76 router.GET("/txn", endpointAccessTransaction) 77 78 // Since the handler function name is used as the transaction name, 79 // anonymous functions do not get usefully named. We encourage 80 // transforming anonymous functions into named functions. 81 router.GET("/anon", func(c *gin.Context) { 82 c.Writer.WriteString("anonymous function handler") 83 }) 84 85 v1 := router.Group("/v1") 86 v1.GET("/login", v1login) 87 v1.GET("/submit", v1submit) 88 v1.GET("/read", v1read) 89 90 router.NoRoute(endpointNotFound) 91 92 router.Run(":8000") 93 }