1 回答

TA贡献2016条经验 获得超9个赞
避免使用全局上下文,而是在入口点创建一个全局上下文,然后将其作为参数传递给需要它的任何函数。
您可以使用Gin框架提供的包。nrgin
并在功能中main()
创建纽瑞克的实例 -
newrelic.NewApplication(cfg)
调用在新功能实例中传递的 - 函数。这会将 Gin 事务上下文键 - 添加到上下文中。
nrgin.Middleware(app)
newRelicTransaction
将步骤 2 中的函数注册为所有路由的中间件 -
router.Use(nrgin.Middleware(app))
然后,您可以将相同的上下文对象传递给可以接受类型的参数的其他函数,因为它只是实现Go的接口。context.Context
gin.Context
context
示例代码
import "github.com/newrelic/go-agent/_integrations/nrgin/v1"
func main() {
cfg := newrelic.NewConfig("Gin App", mustGetEnv("NEW_RELIC_LICENSE_KEY"))
app, err := newrelic.NewApplication(cfg)
if nil != err {
fmt.Println(err)
}
router := gin.Default()
router.Use(nrgin.Middleware(app))
router.GET("/example-get", GetController)
router.Run(":80")
}
func GetController(c *gin.Context) {
if txn := nrgin.Transaction(c); nil != txn {
txn.SetName("custom-name")
}
databaseGet(c)
c.Writer.WriteString("example response...")
}
func databaseGet(c context.Context) {
if txn := nrgin.Transaction(c); nil != txn {
txn.SetName("custom-name")
}
c.Writer.WriteString("example response...")
}
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报