Bind form-data request with custom struct

The follow example using custom struct:

  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. }

Using the command curl command result:

  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"}}

NOTE: NOT support the follow style struct:

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

In a word, only support nested custom struct which have no form now.