How to check for user agent for all requests?

Viewed 60

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 Answers

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