一般通過調用 `c.Request.Body` 方法綁定數據,但不能多次調用這個方法。
```go
type formA struct {
Foo string `json:"foo" xml:"foo" binding:"required"`
}
type formB struct {
Bar string `json:"bar" xml:"bar" binding:"required"`
}
func SomeHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// c.ShouldBind 使用了 c.Request.Body,不可重用。
if errA := c.ShouldBind(&objA); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// 因為現在 c.Request.Body 是 EOF,所以這里會報錯。
} else if errB := c.ShouldBind(&objB); errB == nil {
c.String(http.StatusOK, `the body should be formB`)
} else {
...
}
}
```
要想多次綁定,可以使用 `c.ShouldBindBodyWith`.
```go
func SomeHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// 讀取 c.Request.Body 并將結果存入上下文。
if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// 這時, 復用存儲在上下文中的 body。
} else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
c.String(http.StatusOK, `the body should be formB JSON`)
// 可以接受其他格式
} else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
c.String(http.StatusOK, `the body should be formB XML`)
} else {
...
}
}
```
* `c.ShouldBindBodyWith` 會在綁定之前將 body 存儲到上下文中。 這會對性能造成輕微影響,如果調用一次就能完成綁定的話,那就不要用這個方法。
* 只有某些格式需要此功能,如 `JSON`, `XML`, `MsgPack`,
`ProtoBuf`。 對于其他格式, 如 `Query`, `Form`, `FormPost`, `FormMultipart`
可以多次調用 `c.ShouldBind()` 而不會造成任任何性能損失 (詳見 [#1341](https://github.com/gin-gonic/gin/pull/1341))。
- 介紹
- 快速入門
- 基準測試
- 特性
- 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