主頁 > 知識(shí)庫 > gin使用自定義結(jié)構(gòu)綁定表單數(shù)據(jù)的示例代碼

gin使用自定義結(jié)構(gòu)綁定表單數(shù)據(jù)的示例代碼

熱門標(biāo)簽:網(wǎng)站排名優(yōu)化 鐵路電話系統(tǒng) 地方門戶網(wǎng)站 百度競價(jià)排名 AI電銷 服務(wù)外包 Linux服務(wù)器 呼叫中心市場需求

以下示例使用自定義結(jié)構(gòu)

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()
}

運(yùn)行示例:

$ 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"}}

 

注意:不支持以下樣式結(jié)構(gòu)

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
}

總之,現(xiàn)在只支持現(xiàn)在沒有form標(biāo)簽的自定義結(jié)構(gòu)

到此這篇關(guān)于gin使用自定義結(jié)構(gòu)綁定表單數(shù)據(jù)的示例代碼的文章就介紹到這了,更多相關(guān)gin綁定表單數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Django框架獲取form表單數(shù)據(jù)方式總結(jié)
  • 使用Django Form解決表單數(shù)據(jù)無法動(dòng)態(tài)刷新的兩種方法

標(biāo)簽:崇左 仙桃 湘潭 蘭州 湖南 黃山 衡水 銅川

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《gin使用自定義結(jié)構(gòu)綁定表單數(shù)據(jù)的示例代碼》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266