以下示例使用自定義結構體:
```go
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` 命令結果:
```
$ 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"}}
```
**注意**:不支持以下格式結構體:
```go
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
}
```
總之, 目前僅支持沒有 form 的嵌套結構體。
- 介紹
- 快速入門
- 基準測試
- 特性
- Jsoniter
- 示例
- AsciiJSON
- HTML 渲染
- HTTP2 server 推送
- JSONP
- Multipart/Urlencoded 綁定
- Multipart/Urlencoded 表單
- PureJSON
- Query 和 post form
- SecureJSON
- XML/JSON/YAML/ProtoBuf 渲染
- 上傳文件
- 單文件
- 多文件
- 不使用默認的中間件
- 從 reader 讀取數據
- 優雅地重啟或停止
- 使用 BasicAuth 中間件
- 使用 HTTP 方法
- 使用中間件
- 只綁定 url 查詢字符串
- 在中間件中使用 Goroutine
- 多模板
- 如何記錄日志
- 定義路由日志的格式
- 將 request body 綁定到不同的結構體中
- 支持 Let's Encrypt
- 映射查詢字符串或表單參數
- 查詢字符串參數
- 模型綁定和驗證
- 綁定 HTML 復選框
- 綁定 Uri
- 綁定查詢字符串或表單數據
- 綁定表單數據至自定義結構體
- 自定義 HTTP 配置
- 自定義中間件
- 自定義驗證器
- 設置和獲取 Cookie
- 路由參數
- 路由組
- 運行多個服務
- 重定向
- 靜態文件服務
- 靜態資源嵌入
- 測試
- 用戶
- FAQ