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

目录结构

主目录readJson

  1. —— main.go

代码示例

main.go

  1. package main
  2. import (
  3. "github.com/kataras/iris"
  4. )
  5. type Company struct {
  6. Name string
  7. City string
  8. Other string
  9. }
  10. func MyHandler(ctx iris.Context) {
  11. var c Company
  12. if err := ctx.ReadJSON(&c); err != nil {
  13. ctx.StatusCode(iris.StatusBadRequest)
  14. ctx.WriteString(err.Error())
  15. return
  16. }
  17. ctx.Writef("Received: %#+v\n", c)
  18. }
  19. //简单的json,请阅读https://golang.org/pkg/encoding/json
  20. type Person struct {
  21. Name string `json:"name"`
  22. Age int `json:"age"`
  23. }
  24. // MyHandler2从JSON POST数据中读取Person的集合。
  25. func MyHandler2(ctx iris.Context) {
  26. var persons []Person
  27. err := ctx.ReadJSON(&persons)
  28. if err != nil {
  29. ctx.StatusCode(iris.StatusBadRequest)
  30. ctx.WriteString(err.Error())
  31. return
  32. }
  33. ctx.Writef("Received: %#+v\n", persons)
  34. }
  35. func main() {
  36. app := iris.New()
  37. app.Post("/", MyHandler)
  38. app.Post("/slice", MyHandler2)
  39. //使用Postman或其他什么来做POST请求
  40. //使用RAW BODY到http//localhost:8080:
  41. /*
  42. {
  43. "Name": "iris-Go",
  44. "City": "New York",
  45. "Other": "Something here"
  46. }
  47. */
  48. //和Content-Type到application/json(可选且易用)
  49. //响应应该是:
  50. //接收值: main.Company{Name:"iris-Go", City:"New York", Other:"Something here"}
  51. app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed), iris.WithOptimizations)
  52. }