如何检查所有请求的用户代理?

huangapple go评论79阅读模式
英文:

How to check for user agent for all requests?

问题

我有一个定义用户代理的函数:

func getUserAgent(c *gin.Context) bool {
	ua := ua.Parse(c.Request.UserAgent())
	if ua.Bot {
		return false
	} else {
		return true
	}
}

此外,我有一些路由,我需要在每个路由中调用getUserAgent函数,如果返回true,则使用我的路由,如果返回false,则返回其他内容。我该如何做到这一点?

路由:

func Routes(router *gin.Engine) {

	router.GET("/user_agent", getUserAgent)

	router.GET("/", func(c *gin.Context) {

		c.HTML(http.StatusOK, "index.html", nil)
	})
	router.GET("/:some_urls", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	categories := router.Group("/categories")
	{
		categories.GET("/", controller.GetAllCategories)
	}
	router.GET("/category_detail", controller.GetCategoriesById)
	products := router.Group("/products")
	{
		products.GET("/", controller.GetAllProducts_by_multi_params)
	}
...
英文:

I have a function that defines a user_agent:

func getUserAgent(c *gin.Context) bool {
	ua := ua.Parse(c.Request.UserAgent())
	if ua.Bot {
		return false
	} else {
		return true
	}
}

Also, I have routes, and I need to call getUserAgent in each route and if it true - use my routes , if false - return smth else. How can i do this?

Routes:

func Routes(router *gin.Engine) {

	router.GET("/user_agent", getUserAgent)

	router.GET("/", func(c *gin.Context) {

		c.HTML(http.StatusOK, "index.html", nil)
	})
	router.GET("/:some_urls", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	categories := router.Group("/categories")
	{
		categories.GET("/", controller.GetAllCategories)
	}
	router.GET("/category_detail", controller.GetCategoriesById)
	products := router.Group("/products")
	{
		products.GET("/", controller.GetAllProducts_by_multi_params)
	}
...

答案1

得分: 2

也许你可以将getUserAgent作为中间件,像下面这样:
每个路由器都会先经过getUserAgent,然后再运行处理程序。

router.Use(getUserAgent)
英文:

Maybe you can make the getUserAgent as middleware like below
every router will go into the getUserAgent first then run the handler.

router.Use(getUserAgent)

huangapple
  • 本文由 发表于 2022年8月13日 21:29:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/73344708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定