iris自定义结构体映射获取xml格式请求数据

目录结构

主目录readXml

  1. —— main.go
  2. —— main_test.go

代码示例

main.go

  1. package main
  2. import (
  3. "encoding/xml"
  4. "github.com/kataras/iris"
  5. "fmt"
  6. )
  7. func main() {
  8. app := newApp()
  9. //使用Postman或其他什么来做POST请求
  10. //使用RAW BODY到http//localhost:8080/
  11. /*
  12. <person name="Winston Churchill" age="90">
  13. <description>Description of this person, the body of this inner element.</description>
  14. </person>
  15. */
  16. //和Content-Type到application/xml(可选但最好设置)
  17. //响应应该是:
  18. // 接收: main.person{XMLName:xml.Name{Space:"", Local:"person"}, Name:"Winston Churchill", Age:90,
  19. // Description:"Description of this person, the body of this inner element."}
  20. app.Run(iris.Addr(":8080"), iris.WithOptimizations)
  21. }
  22. func newApp() *iris.Application {
  23. app := iris.New()
  24. app.Post("/", handler)
  25. return app
  26. }
  27. //简单的xml例子,请访问https://golang.org/pkg/encoding/xml
  28. type person struct {
  29. XMLName xml.Name `xml:"person"` //元素名称
  30. Name string `xml:"name,attr"` //,attr属性。
  31. Age int `xml:"age,attr"` //,attr属性。
  32. Description string `xml:"description"` //内部元素名称,值是它的主体。
  33. }
  34. func handler(ctx iris.Context) {
  35. fmt.Println(ctx.GetCurrentRoute())
  36. var p person
  37. if err := ctx.ReadXML(&p); err != nil {
  38. fmt.Println(err)
  39. ctx.StatusCode(iris.StatusBadRequest)
  40. ctx.WriteString(err.Error())
  41. return
  42. }
  43. ctx.Writef("Received: %#+v", p)
  44. }

main_test.go

  1. package main
  2. import (
  3. "testing"
  4. "github.com/kataras/iris/httptest"
  5. )
  6. func TestReadXML(t *testing.T) {
  7. app := newApp()
  8. e := httptest.New(t, app)
  9. expectedResponse := `Received: main.person{XMLName:xml.Name{Space:"", Local:"person"}, Name:"Winston Churchill", Age:90, Description:"Description of this person, the body of this inner element."}`
  10. send := `<person name="Winston Churchill" age="90"><description>Description of this person, the body of this inner element.</description></person>`
  11. e.POST("/").WithText(send).Expect().
  12. Status(httptest.StatusOK).Body().Equal(expectedResponse)
  13. }