绑定表单数据至自定义结构体

以下示例使用自定义结构体:

  1. type StructA struct {
  2. FieldA string `form:"field_a"`
  3. }
  4. type StructB struct {
  5. NestedStruct StructA
  6. FieldB string `form:"field_b"`
  7. }
  8. type StructC struct {
  9. NestedStructPointer *StructA
  10. FieldC string `form:"field_c"`
  11. }
  12. type StructD struct {
  13. NestedAnonyStruct struct {
  14. FieldX string `form:"field_x"`
  15. }
  16. FieldD string `form:"field_d"`
  17. }
  18. func GetDataB(c *gin.Context) {
  19. var b StructB
  20. c.Bind(&b)
  21. c.JSON(200, gin.H{
  22. "a": b.NestedStruct,
  23. "b": b.FieldB,
  24. })
  25. }
  26. func GetDataC(c *gin.Context) {
  27. var b StructC
  28. c.Bind(&b)
  29. c.JSON(200, gin.H{
  30. "a": b.NestedStructPointer,
  31. "c": b.FieldC,
  32. })
  33. }
  34. func GetDataD(c *gin.Context) {
  35. var b StructD
  36. c.Bind(&b)
  37. c.JSON(200, gin.H{
  38. "x": b.NestedAnonyStruct,
  39. "d": b.FieldD,
  40. })
  41. }
  42. func main() {
  43. r := gin.Default()
  44. r.GET("/getb", GetDataB)
  45. r.GET("/getc", GetDataC)
  46. r.GET("/getd", GetDataD)
  47. r.Run()
  48. }

使用 curl 命令结果:

  1. $ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
  2. {"a":{"FieldA":"hello"},"b":"world"}
  3. $ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
  4. {"a":{"FieldA":"hello"},"c":"world"}
  5. $ curl "http://localhost:8080/getd?field_x=hello&field_d=world"
  6. {"d":"world","x":{"FieldX":"hello"}}

注意:不支持以下格式结构体:

  1. type StructX struct {
  2. X struct {} `form:"name_x"` // 有 form
  3. }
  4. type StructY struct {
  5. Y StructX `form:"name_y"` // 有 form
  6. }
  7. type StructZ struct {
  8. Z *StructZ `form:"name_z"` // 有 form
  9. }

总之, 目前仅支持没有 form 的嵌套结构体。