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

发布时间:2020-11-03 14:39:17 作者:Leah
来源:亿速云 阅读:148

今天就跟大家聊聊有关gin使用自定义结构实现绑定表单数据,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

以下示例使用自定义结构

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使用自定义结构实现绑定表单数据有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. 如何使用IDA自定义数据结构?
  2. 怎么在Vue中使用表单控件数据绑定

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

gin

上一篇:使用C++实现保存txt文件

下一篇:使用python 实现批量图片识别并翻译的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》