gin
gin copied to clipboard
Can I used middleware like this?
I want to divide log path by parameters, so I used middleware below.
router.Use(gomiddleware.ApacheFormatLogger(constants.LogDirectory+"/pc_nx.access", func(c *gin.Context) bool {
param := models.NewParam(c)
return param.IsPCNX()
}))
router.Use(gomiddleware.ApacheFormatLogger(constants.LogDirectory+"/mobile_nx.access", func(c *gin.Context) bool {
param := models.NewParam(c)
return param.IsMobileNX()
}))
But I want to call a models.NewParams
just once.
So I changed code like below, but I've never seen it used like this, so I'm not sure if it's okay.
Is there any problem when I change it like this?
var param *models.Param
router.Use(func(c *gin.Context) {
param = models.NewParam(c)
})
logPath := constants.LogDirectory
if param.IsPCNX() {
logPath += "/pc_nx.access"
} else if param.IsMobileNX() {
logPath += "/mobile_nx.access"
}
router.Use(gomiddleware.ApacheFormatLogger(logPath, func(c *gin.Context) bool {
return true
}))
are you want to collect log by diff uri?
engine := gin.New()
engine.Use(func(ctx *gin.Context) {
uri := ctx.Request.RequestURI
switch {
case strings.Contains(uri, "pc"):
ctx.Set("log_path", "pc_nx.access")
case strings.Contains(uri, "mobile"):
ctx.Set("log_path", "mobile_nx.access")
}
ctx.Next()
})
fnWriter := func(lp, msg string) {
// do log write
}
engine.Handle(http.MethodGet, "mobile/hi", func(ctx *gin.Context) {
lp := ctx.GetString("log_path")
// collect mobile log
fnWriter(lp, "mobile method log collect")
})
engine.Handle(http.MethodGet, "pc/hi", func(ctx *gin.Context) {
lp := ctx.GetString("log_path")
// collect pc log
fnWriter(lp, "pc method log collect")
})