英文:
Go GIN context parse unexpected query string
问题
我在REST请求中有不同的结构体用于查询。当查询字符串包含我结构体中未预期的参数时,我想返回HTTP 400: BAD REQUEST
。
type FilterData struct {
Filter1 string `form:"filter_1"`
Filter2 string `form:"filter_2"`
Filter3 string `form:"filter_3"`
}
期望的请求是localhost:8000/testing?filter_1=123456&filter_2=test&filter_3=golang
。
但是,如果请求是localhost:8000/users?FILTER1=123456&filter_2=test&filter_3=golang
或者包含任何额外的参数,而不是我预期的结构体,我想返回bad request
。
Go的gin.Context
有一个函数c.ShouldBindQuery(&filterData)
,但是这会将filter_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
得分: 1
在API中,忽略未知的查询参数是相当标准的做法。如果你要求某些参数始终具有值,可以在你的结构标签中使用binding:"required"
属性。
如果你希望在出现未知查询参数时返回400错误,你需要检查c.Request.URL.Query()
的内容。
英文:
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()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论