Golang Gin 绑定请求正文 XML 到切片

我对 Gin 中的默认绑定有疑问。我有一个传入请求,其中主体是多个 Entity 对象,如下所示:


<Entity>

  <Name>Name One here</Name>

  ...

</Entity>

<Entity>

  <Name>Name Two here</Name>

  ...

</Entity>

我的目标是将它映射到相应的切片。所以所需对象的结构是这样的:


type Entity struct {

  XMLName xml.Name `bson:"-" json:"-" xml:"Entity"`

  Name   string    `bson:"name,omitempty" json:",omitempty" xml:",omitempty"`

  ...

}

我遇到的问题是,无论在请求正文中传递了多少对象,都只有一个提供的对象被映射到切片中。请注意,请求的 JSON 版本可以正确解析。


[

 {

   Name: "Name One",

   ...

 },

 {

   Name: "Name Two",

   ...

 }

]

我有一个模型请求结构的结构


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 的解析,并且适用于我需要的所有其他场景。


希望这提供了足够的上下文,任何帮助将不胜感激!谢谢!


慕尼黑8549860
浏览 114回答 1
1回答

慕仙森

这不是杜松子酒问题:&nbsp;unmarshal-xml-array-in-golang-only-getting-the-first-element以下是两种处理方法:添加一个根节点就像@zangw通过'for'更改绑定方法&nbsp;github.com\gin-gonic\gin@v1.8.1\binding\xml.go&nbsp;line 28&nbsp;func decodeXML从func decodeXML(r io.Reader, obj any) error {&nbsp; &nbsp; decoder := xml.NewDecoder(r)&nbsp; &nbsp; if err := decoder.Decode(obj); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; return validate(obj)}到func decodeXML(r io.Reader, obj any) error {&nbsp; &nbsp; decoder := xml.NewDecoder(r)&nbsp; &nbsp; for&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if err := decoder.Decode(obj); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err == io.EOF{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return validate(obj)}
打开App,查看更多内容
随时随地看视频慕课网APP