go將request?body綁定到不同的結構體中教程
c.Request.Body 方法綁定數(shù)據(jù)
一般通過調用 c.Request.Body 方法綁定數(shù)據(jù),但不能多次調用這個方法。
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`)
// 因為現(xiàn)在 c.Request.Body 是 EOF,所以這里會報錯。
} 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{}
// 讀取 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() 而不會造成任任何性能損失,詳見
以上就是go將request body綁定到不同的結構體中教程的詳細內容,更多關于go request body綁定結構體的資料請關注腳本之家其它相關文章!
相關文章
Go語言中html/template模塊詳細功能介紹與示例代碼
這篇文章主要介紹了Go語言中html/template模塊詳細功能介紹與示例代碼,這里說的是go 語言中自帶的包html/template里的一些基本操作,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-03-03

