gin架構26--綁定表單資料至自定義結構體
- 介紹
- 案例
- 說明
介紹
本文介紹 如何綁定表單資料至自定義結構體,并加以案例說明。
案例
源碼:
package main
import "github.com/gin-gonic/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()
}
測試:
http://127.0.0.1:8080/getb?field_a=hello&field_b=world
{
"a": {
"FieldA": "hello"
},
"b": "world"
}
http://127.0.0.1:8080/getc?field_a=hello&field_c=world
{
"a": {
"FieldA": "hello"
},
"c": "world"
}
http://127.0.0.1:8080/getd?field_x=hello&field_d=world
{
"d": "world",
"x": {
"FieldX": "hello"
}
}
注意:目前僅支援沒有 form 的嵌套結構體, 不支援以下格式結構體:
type StructX struct {
X struct {} `form:"name_x"` // 有 form
}
type StructY struct {
Y StructX `form:"name_y"` // 有 form
}
type StructZ struct {
Z *StructZ `form:"name_z"` // 有 form
}
說明
gin官方文檔 綁定表單資料至自定義結構體