Example code of binding form data by 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 *gin.Context) {
  var b StructB
  c.JSON(200, gin.H{
    "a": b.NestedStruct,
    "b": b.FieldB,
func GetDataC(c *gin.Context) {
  var b StructC
  c.JSON(200, gin.H{
    "a": b.NestedStructPointer,
    "c": b.FieldC,
func GetDataD(c *gin.Context) {
  var b StructD
  c.JSON(200, gin.H{
    "x": b.NestedAnonyStruct,
    "d": b.FieldD,
func main() {
  r := gin.Default()
  r.GET("/getb", GetDataB)
  r.GET("/getc", GetDataC)
  r.GET("/getd", GetDataD)

Running example:

$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"


be careful: the following style structures are 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

In short, we only support it now, but not nowformCustom structure of label

Here is the article about the example code of binding form data with custom structure in gin. For more information about binding form data with gin, please search previous articles of developer or continue to browse the following articles. I hope you can support developer more in the future!