gin icon indicating copy to clipboard operation
gin copied to clipboard

Can I used middleware like this?

Open previc opened this issue 1 year ago • 1 comments

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
	}))

previc avatar Jul 20 '22 08:07 previc

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")
	})

0x2d3c avatar Jul 27 '22 02:07 0x2d3c