gin使用自定义结构绑定表单数据的示例代码
以下示例使用自定义结构
typeStructAstruct{
FieldAstring`form:"field_a"`
}
typeStructBstruct{
NestedStructStructA
FieldBstring`form:"field_b"`
}
typeStructCstruct{
NestedStructPointer*StructA
FieldCstring`form:"field_c"`
}
typeStructDstruct{
NestedAnonyStructstruct{
FieldXstring`form:"field_x"`
}
FieldDstring`form:"field_d"`
}
funcGetDataB(c*gin.Context){
varbStructB
c.Bind(&b)
c.JSON(200,gin.H{
"a":b.NestedStruct,
"b":b.FieldB,
})
}
funcGetDataC(c*gin.Context){
varbStructC
c.Bind(&b)
c.JSON(200,gin.H{
"a":b.NestedStructPointer,
"c":b.FieldC,
})
}
funcGetDataD(c*gin.Context){
varbStructD
c.Bind(&b)
c.JSON(200,gin.H{
"x":b.NestedAnonyStruct,
"d":b.FieldD,
})
}
funcmain(){
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"}}
注意:不支持以下样式结构
typeStructXstruct{
Xstruct{}`form:"name_x"`//HEREhaveform
}
typeStructYstruct{
YStructX`form:"name_y"`//HEREhaveform
}
typeStructZstruct{
Z*StructZ`form:"name_z"`//HEREhaveform
}
总之,现在只支持现在没有form标签的自定义结构
到此这篇关于gin使用自定义结构绑定表单数据的示例代码的文章就介绍到这了,更多相关gin绑定表单数据内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下