我对Gin中的默认绑定有问题.我有一个传入的请求,其中主体是多个实体对象,如下所示:
<Entity>
<Name>Name One here</Name>
...
</Entity>
<Entity>
<Name>Name Two here</Name>
...
</Entity>
我的目标是将其映射到相应的切片.因此,所需对象的 struct 如下所示:
type Entity struct {
XMLName xml.Name `bson:"-" json:"-" xml:"Entity"`
Name string `bson:"name,omitempty" json:",omitempty" xml:",omitempty"`
...
}
我遇到的问题是,无论请求正文中传递了多少对象,都会将only one个提供的对象映射到片中.请注意,请求的JSON版本可以正确解析.
[
{
Name: "Name One",
...
},
{
Name: "Name Two",
...
}
]
我有一个用于对请求 struct 建模的 struct
type ApplicationRequest struct {
XMLName xml.Name `bson:"-" xml:"Entities"`
Entities []Entity `binding:"required" xml:"Entity"`
ParameterOne bool
...
}
因此,现在在控制器函数中,我按如下方式处理绑定:
func RequestHandler() gin.HandlerFunc {
return func(c *gin.Context) {
var request ApplicationRequest
if err := c.Bind(&request.Entities); err != nil {
responseFunction(http.StatusBadRequest, ..., Message: err.Error()})
return
}
// At this point, the request.Entities slice has ONE element, never more than one
}
}
注意,我使用的是gin context.Bind(...)函数,因为它隐式地处理JSON或XML的解析,并且适用于我需要的所有其他场景.
希望这能提供足够的背景,任何帮助都将不胜感激!谢谢!