gin绑定表单数据 gin使用自定义结构绑定表单数据的代码实例
晨梦~思雨 人气:0想了解gin使用自定义结构绑定表单数据的代码实例的相关内容吗,晨梦~思雨在本文为您仔细讲解gin绑定表单数据的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:gin绑定表单数据,gin自定义结构,下面大家一起来学习吧。
以下示例使用自定义结构
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.Bind(&b) c.JSON(200, gin.H{ "a": b.NestedStruct, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(200, gin.H{ "a": b.NestedStructPointer, "c": b.FieldC, }) } func GetDataD(c *gin.Context) { var b StructD c.Bind(&b) 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) r.Run() }
运行示例:
$ 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"` // 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 }
总之,现在只支持现在没有form
标签的自定义结构
加载全部内容