对于复杂的表单,使用自定义结构体嵌套完成绑定。

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

package main

import "github.com/gin-gonic/gin"

type StructA struct {
	FieldA string `form:"field_a"`
}

type StructB struct {
	NestedStruct StructA
	FiledB 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(context *gin.Context) {
	var b StructB
	context.Bind(&b)
	context.JSON(200, gin.H{
		"a": b.NestedStruct,
		"b": b.FiledB,
	})
}

func GetDataC(context *gin.Context) {
	var c StructC
	context.Bind(&c)
	context.JSON(200, gin.H{
		"a": c.NestedStructPointer,
		"c": c.FieldC,
	})
}

func GetDataD(context *gin.Context) {
	var d StructD
	context.Bind(&d)
	context.JSON(200, gin.H{
		"x": d.NestedAnonyStruct,
		"d": d.FieldD,
	})
}

func main() {
	r := gin.Default()
	r.GET("/getb", GetDataB)
	r.GET("/getc", GetDataC)
	r.GET("/getd", GetDataD)
	r.Run()
}

使用 curl 命令结果:

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

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

type StructX struct {
    X struct {} `form:"name_x"` // 有 form
}

type StructY struct {
    Y StructX `form:"name_y"` // 有 form
}

type StructZ struct {
    Z *StructZ `form:"name_z"` // 有 form
}

tag 标签映射只能在定义结构体时给具体的字段设置,在引用结构体时不能复写。总之, 目前仅支持没有 form 的嵌套结构体。