gin将请求体绑定到不同的结构体中
生活随笔
收集整理的這篇文章主要介紹了
gin将请求体绑定到不同的结构体中
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
gin將請求體綁定到不同的結構體中
綁定請求體的常規方法使用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()多次調用而不影響性能
總結
以上是生活随笔為你收集整理的gin将请求体绑定到不同的结构体中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gin HTTP/2 服务器推送
- 下一篇: 程序员笑话二十七