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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

c.Request.URL.Query() returns map[string][]string like given in this answer. when I loop through these keys, how can I compare that is the string in my struct?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.