將請求體繫結到不同的結構體中
阿新 • • 發佈:2020-06-27
package main import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "net/http" ) type formA struct { Foo string `json:"foo" xml:"foo" binding:"required"` } type formB struct { Bar string `json:"bar" xml:"bar" binding:"required"` } // 繫結請求體的常規方法使用c.Request.Body,並且不能多次呼叫 func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} if errA := c.ShouldBind(&objA); errA == nil { c.String(http.StatusOK, `the body should be formA`) } else if errB := c.ShouldBind(&objB); errB == nil { c.String(http.StatusOK, `the body should be formB`) } else { } } //同樣,你能使用c.ShouldBindBodyWith func SomeHandler2(c *gin.Context) { objA := formA{} objB := formB{} if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil { c.String(http.StatusOK, `the body should be formA`) } 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 { } }