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绑定表单数据内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!