Reputation: 390
I have different structs for the query in the REST
request. I'd like to return HTTP 400: BAD REQUEST
when the query string contains an unexpected parameter than my struct.
type FilterData struct {
Filter1 string `form:"filter_1"`
Filter2 string `form:"filter_2"`
Filter3 string `form:"filter_3"`
}
The expected request request is localhost:8000/testing?filter_1=123456&filter_2=test&filter_3=golang
But if the is request like localhost:8000/users?FILTER1=123456&filter_2=test&filter_3=golang
or any extra parameter than my expected struct I want to return bad request
.
Go gin.Context
has c.ShouldBindQuery(&filterData)
but this returns the filter_1
as an empty string, indeed in my case that's a bad request.
How would I do an extra check with a common function to all requests?
PS. some values in this struct can be optional.
Upvotes: 1
Views: 3547
Reputation: 432
It is pretty standard in apis to ignore unknown query parameters. If you require some parameters to always have value, use binding:"required"
property in your struct tags.
https://github.com/gin-gonic/gin#model-binding-and-validation
If you want to throw back a 400 on unknown query params, you must check contents of c.Request.URL.Query()
.
Upvotes: 1