gin使用自定义结构绑定表单数据
生活随笔
收集整理的這篇文章主要介紹了
gin使用自定义结构绑定表单数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
gin使用自定義結構綁定表單數據
以下示例使用自定義結構
type StructA struct {FieldA string `form:"field_a"` }type StructB struct {NestedStruct StructAFieldB string `form:"field_b"` }type StructC struct {NestedStructPointer *StructAFieldC 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 StructBc.Bind(&b)c.JSON(200, gin.H{"a": b.NestedStruct,"b": b.FieldB,}) }func GetDataC(c *gin.Context) {var b StructCc.Bind(&b)c.JSON(200, gin.H{"a": b.NestedStructPointer,"c": b.FieldC,}) }func GetDataD(c *gin.Context) {var b StructDc.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標簽的自定義結構
總結
以上是生活随笔為你收集整理的gin使用自定义结构绑定表单数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序员笑话二十七
- 下一篇: gin构建包含模板的二进制文件