我正在main.go中创建新的遗物事务,并且必须将其传递给处理程序,然后传递到控制器等。有没有办法我可以全局定义它,然后可以在任何处理程序,控制器或数据库事务中访问?
import(
"github.com/gin-gonic/gin"
newrelic "github.com/newrelic/go-agent"
)
// main.go
func newrelicHandler() (gin.HandlerFunc, newrelic.Application) {
newrelicConfig := newrelic.NewConfig("NEW_RELIC_APP_NAME", "NEW_RELIC_APP_KEY")
app, err := newrelic.NewApplication(newrelicConfig)
if err != nil {
return func(c *gin.Context) {
c.Next()
}, app
}
return func(c *gin.Context) {
txn := app.StartTransaction(c.Request.URL.Path, c.Writer, c.Request)
c.Set("newRelicTransaction", txn)
apm, ok := c.Get("newRelicTransaction")
defer txn.End()
c.Next()
}, app
}
func main() {
r := gin.New()
x, app := newrelicHandler()
r.Use(x)
}
// test/handler.go
func (t *TestHandler) Display(c *gin.Context) {
apmTxn, ok := c.Get("newRelicTransaction")
test, err := t.testCtrl.Display(apmTxn)
if err != nil {
return err
}
c.JSON(http.StatusOK, gin.H{"message": "success"})
}
// test/controller.go
func (t *TestCtrl) Display(txn interface{}) {
apmTxn, ok := txn.(newrelic.Transaction)
if !ok {
fmt.Println("ERR")
}
segment := newrelic.StartSegment(apmTxn, "SomeSegmentName")
// get data
segment.End()
return
}
慕沐林林
相关分类