SoFunction
Updated on 2025-03-04

Example code for gin to bind form data using custom structure

The following example uses a custom structure

type StructA struct {
  FieldA string `form:"field_a"`
}
 
type StructB struct {
  NestedStruct StructA
  FieldB string `form:"field_b"`
}
 
type StructC struct {
  NestedStructPointer *StructA
  FieldC string `form:"field_c"`
}
 
type StructD struct {
  NestedAnonyStruct struct {
    FieldX string `form:"field_x"`
  }
  FieldD string `form:"field_d"`
}
 
func GetDataB(c *) {
  var b StructB
  (&b)
  (200, {
    "a": ,
    "b": ,
  })
}
 
func GetDataC(c *) {
  var b StructC
  (&b)
  (200, {
    "a": ,
    "c": ,
  })
}
 
func GetDataD(c *) {
  var b StructD
  (&b)
  (200, {
    "x": ,
    "d": ,
  })
}
 
func main() {
  r := ()
  ("/getb", GetDataB)
  ("/getc", GetDataC)
  ("/getd", GetDataD)
 
  ()
}

Running example:

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

 

Notice: The following style structure is not supported

type StructX struct {
  X struct {} `form:"name_x"` // HERE have form
}
 
type StructY struct {
  Y StructX `form:"name_y"` // HERE have form
}
 
type StructZ struct {
  Z *StructZ `form:"name_z"` // HERE have form
}

Anyway, it only supports now withoutformCustom structure of tags

This is the article about the example code for gin binding form data using custom structure. For more related gin binding form data content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!