1

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.

Taylan Yuksel
  • 345
  • 3
  • 12

1 Answers1

1

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

potato_cannon
  • 283
  • 2
  • 9
  • `c.Request.URL.Query()` returns `map[string][]string` like given [in this answer.](https://stackoverflow.com/a/15408779/15213512) when I loop through these keys, how can I compare that is the string in my struct? – Taylan Yuksel Mar 17 '22 at 09:16
  • 1
    You have already hardcoded the valid parameters on your struct. Just check each key on the query map against a list of valid keys. If any key in the query map is not one of filter_1, filter_2 or filter_3, you can hit back that 400. If you want something general, you have to take a look at reflect package. Figure out a way to get struct fields and check query keys against valid fields that way. – potato_cannon Mar 17 '22 at 20:07