Go GIN上下文解析意外的查询字符串

huangapple go评论78阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年3月17日 00:10:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/71500514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定