欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

gin使用自定义结构绑定表单数据

发布时间:2025/6/15 编程问答 26 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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使用自定义结构绑定表单数据的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。