英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论