綁定請求體的常規方法使用`c.Request.Body`,并且不能多次調用
```
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{}
// This c.ShouldBind consumes c.Request.Body and it cannot be reused.
if errA := c.ShouldBind(&objA); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// Always an error is occurred by this because c.Request.Body is EOF now.
} else if errB := c.ShouldBind(&objB); errB == nil {
c.String(http.StatusOK, `the body should be formB`)
} else {
...
}
}
```
同樣,你能使用`c.ShouldBindBodyWith`
```
func SomeHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// This reads c.Request.Body and stores the result into the context.
if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// At this time, it reuses body stored in the context.
} else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
c.String(http.StatusOK, `the body should be formB JSON`)
// And it can accepts other formats
} 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))
- 簡介
- 安裝
- 快速入門
- 代碼示例
- 使用 GET, POST, PUT, PATCH, DELETE, OPTIONS
- 獲取路徑中的參數
- 獲取Get參數
- 獲取Post參數
- Get + Post 混合
- 上傳文件
- 路由分組
- 無中間件啟動
- 使用中間件
- 寫日志文件
- 自定義日志格式
- 模型綁定和驗證
- 自定義驗證器
- 只綁定Get參數
- 綁定Get參數或者Post參數
- 綁定uri
- 綁定HTML復選框
- 綁定Post參數
- XML、JSON、YAML和ProtoBuf 渲染(輸出格式)
- 設置靜態文件路徑
- 返回第三方獲取的數據
- HTML渲染
- 多個模板文件
- 重定向
- 自定義中間件
- 使用BasicAuth()(驗證)中間件
- 中間件中使用Goroutines
- 自定義HTTP配置
- 支持Let's Encrypt證書
- Gin運行多個服務
- 優雅重啟或停止
- 構建包含模板的二進制文件
- 使用自定義結構綁定表單數據
- 將請求體綁定到不同的結構體中
- HTTP/2 服務器推送
- 自定義路由日志的格式
- 設置并獲取cookie
- 測試
- 用戶