Casper
Casper

Reputation: 313

How to check for user agent for all requests?

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

Upvotes: 1

Views: 1744

Answers (2)

You can make it a middleware like this:

package middlewares

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func CheckUserAgent() gin.HandlerFunc {
    return func(c *gin.Context) {
        ua := ua.Parse(c.Request.UserAgent())
        
        if ua.Bot {
            c.AbortWithStatus(http.StatusForbidden)
            return
        }

        c.Next()
    }
}

Please note that you need to import 'ua' from your package as well. Then add the middleware to the routes you need to protect like this:

products := router.Group("/products")
{
    products.GET("/", middlewares.CheckUserAgent(), controller.GetAllProducts_by_multi_params)
}

Upvotes: 0

NoahFan
NoahFan

Reputation: 106

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)

Upvotes: 3

Related Questions