您现在的位置是:网站首页> 编程资料编程资料
gin使用自定义结构绑定表单数据的示例代码_Golang_
2023-05-26
448人已围观
简介 gin使用自定义结构绑定表单数据的示例代码_Golang_
以下示例使用自定义结构
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标签的自定义结构
到此这篇关于gin使用自定义结构绑定表单数据的示例代码的文章就介绍到这了,更多相关gin绑定表单数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- 浅析goland等待锁问题_Golang_
- 关于go语言编码需要放到src 文件夹下的问题_Golang_
- Goland 2020或2019软件版本去掉a...或fmt...提示的方法_Golang_
- goland 搭建 gin 框架的步骤详解_Golang_
- Golang单元测试与覆盖率的实例讲解_Golang_
- Goland激活码破解永久版及安装详细教程(亲测可以)_Golang_
- logrus hook输出日志到本地磁盘的操作_Golang_
- Goland 的安装及激活教程(window、linux下安装)_Golang_
- go日志系统logrus显示文件和行号的操作_Golang_
- Gin golang web开发模型绑定实现过程解析_Golang_
