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()多次呼叫而不影響性能
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/201523.html
標籤:其他
下一篇:NodeJS實作JWT原理
