Is it possible to require that certain query parameters are passed to a route? I don't want to use a standard parameter due to the organization of my routes.
Comment From: liuliqiang
Hi @ayushgun ,
Do your the certain query parameters like this?
router.GET("/[foo|bar]", handler) # only match /foo or /bar
router.GET("/", handler) # handler other URI
Comment From: ayushgun
Hi @ayushgun ,
Do your the certain query parameters like this?
router.GET("/[foo|bar]", handler) # only match /foo or /bar router.GET("/", handler) # handler other URI
Hi, thanks for the response! I would like my query parameters to look like this: /endpoint?param=value
where "endpoint" is the name of the route, param is the name of the parameter, and value is some value.
I would like to mandate that these params must be passed when making a request at that endpoint.
Comment From: liuliqiang
Hi @ayushgun looks like you want a validator for the request params. It may implemented by the gin's builtin validator: A guide about it
I don't known whether this code can help you:
type Login struct {
User string `form:"user" json:"user" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
loginInfo := Login{}
if err := c.BindQuery(&loginInfo); err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, loginInfo)
})
http.ListenAndServe(":8080", router)
}
Comment From: Kamandlou
You can use middleware for this, create a custom middleware, and into the middleware check the parameter exists or not. Like this:
testGroup := router.Group("/test").Use(testMiddleWare())
testGroup.GET("/a", controllers.Testa)
testGroup.GET("/b", controllers.Testb)
testGroup.GET("/c", controllers.Testc)
Comment From: julianinsua
I don't know if this is going to help, but since I fell for it, here it goes.
Gin interprets zero values as not there. So let's say you want to pass an integer through the query params, a perfect example would be pagination params, you can't make it required and make it zero-based. Like if you want to pass url?page=0
and make that parameter required, you will get a validation error. Just in case what you are planning to pass there can be 0.