How to get the xml sent by post in a REST API

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

How to get the xml sent by post in a REST API

问题

我想构建一个 REST 应用程序,在其中我需要获取通过 POST 发送的 XML 值。如何恢复数据?

我正在使用 Echo 框架。

英文:

I want to build a rest app in which I have to get the values ​​that are sent by post as xml. How is the data recovered?

I'm using echo framework.

答案1

得分: 1

你需要使用Echo的绑定功能,结合结构标签来提供你期望的XML键的名称。

type DoThingRequest struct {
    Name string `xml:"name"`
}
e.POST("/do_thing", func(c echo.Context) (err error) {
  body := new(DoThingRequest)
  if err := c.Bind(body); err != nil {
    return
  }
  
  // 做一些操作...
}

请参考https://echo.labstack.com/guide/binding/了解更多关于绑定的信息和选项。

英文:

You'll want to use the Binding functionality of Echo, in combination with struct tags to provide the names you expect the XML keys to be.

type DoThingRequest struct {
    Name string `xml:"name"`
}
e.POST("/do_thing", func(c echo.Context) (err error) {
  body := new(DoThingRequest)
  if err := c.Bind(body); err != nil {
    return
  }
  
  // Do some stuff...
}

See https://echo.labstack.com/guide/binding/ for more information and options for binding.

答案2

得分: 0

你可以使用以下函数,其中"value"对应于包装器标签名称。

func xmlEndpoint(c echo.Context) error {
    // 从请求体中获取xml
    xml := c.Request().Body
    // 解析xml
    var data map[string]interface{}
    if err := xml.Unmarshal(data); err != nil {
        return err
    }
    // 从xml中获取值
    value := data["value"].(string)
}

请注意,这只是一个示例函数,你可能需要根据你的实际需求进行适当的修改。

英文:

you can use following function, where "value" corresponds to wrapper tag name.

func xmlEndpoint(c echo.Context) error {
    // get xml from request body
    xml := c.Request().Body
    // parse xml
    var data map[string]interface{}
    if err := xml.Unmarshal(data); err != nil {
	    return err
    }
    // get value from xml
    value := data["value"].(string)
}

huangapple
  • 本文由 发表于 2021年8月16日 22:30:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/68804581.html
匿名

发表评论

匿名网友

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

确定