go將request?body綁定到不同的結(jié)構(gòu)體中教程
c.Request.Body 方法綁定數(shù)據(jù)
一般通過調(diào)用 c.Request.Body 方法綁定數(shù)據(jù),但不能多次調(diào)用這個方法。
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 并將結(jié)果存入上下文。 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 存儲到上下文中。 這會對性能造成輕微影響,如果調(diào)用一次就能完成綁定的話,那就不要用這個方法。
只有某些格式需要此功能,如 JSON, XML, MsgPack, ProtoBuf。
對于其他格式,如 Query, Form, FormPost, FormMultipart 可以多次調(diào)用 c.ShouldBind() 而不會造成任任何性能損失,詳見
以上就是go將request body綁定到不同的結(jié)構(gòu)體中教程的詳細內(nèi)容,更多關(guān)于go request body綁定結(jié)構(gòu)體的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Go?內(nèi)聯(lián)優(yōu)化讓程序員愛不釋手
這篇文章主要介紹了Go?內(nèi)聯(lián)優(yōu)化讓程序員愛不釋手,內(nèi)聯(lián)是在編譯過程中自動進行的一類基本優(yōu)化之一,文章圍繞主題展開更多詳細介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06Go?不支持?[]T轉(zhuǎn)換為[]interface類型詳解
這篇文章主要為大家介紹了Go不支持[]T轉(zhuǎn)換為[]interface類型詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01Go語言中html/template模塊詳細功能介紹與示例代碼
這篇文章主要介紹了Go語言中html/template模塊詳細功能介紹與示例代碼,這里說的是go 語言中自帶的包html/template里的一些基本操作,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-03-03Golang之sync.Pool對象池對象重用機制總結(jié)
這篇文章主要對Golang的sync.Pool對象池對象重用機制做了一個總結(jié),文中有相關(guān)的代碼示例和圖解,具有一定的參考價值,需要的朋友可以參考下2023-07-07