• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    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=hellofield_b=world"
    {"a":{"FieldA":"hello"},"b":"world"}
    $ curl "http://localhost:8080/getc?field_a=hellofield_c=world"
    {"a":{"FieldA":"hello"},"c":"world"}
    $ curl "http://localhost:8080/getd?field_x=hellofield_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绑定表单数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    您可能感兴趣的文章:
    • Django框架获取form表单数据方式总结
    • 使用Django Form解决表单数据无法动态刷新的两种方法
    上一篇:浅析goland等待锁问题
    下一篇:go开发中引用静态库.a文件的方法
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯 版权所有

    《增值电信业务经营许可证》 苏ICP备15040257号-8

    gin使用自定义结构绑定表单数据的示例代码 gin,使用,自定义,结构,绑定,