網(wǎng)站制作哪家實(shí)惠seo權(quán)重優(yōu)化軟件
controller 模型綁定與參數(shù)校驗(yàn)
gin框架提供了多種方法可以將請(qǐng)求體的內(nèi)容綁定到對(duì)應(yīng)struct上,并且提供了一些預(yù)置的參數(shù)校驗(yàn)
綁定方法
根據(jù)數(shù)據(jù)源和類型的不同,gin提供了不同的綁定方法
- Bind, shouldBind: 從form表單中去綁定對(duì)象
- BindJSON, shouldBindJSON: 這兩個(gè)方法是從json表單中去綁定對(duì)象
- 還有從xml,protobuf等等
參數(shù)校驗(yàn)
gin提供了一系列預(yù)置的參數(shù)校驗(yàn),可以參考官方文檔。 用binding 標(biāo)簽
-
required 必須參數(shù)
-
number 要求數(shù)字
-
omitempty 允許為空
-
email 郵件格式
等等
實(shí)例
package courseimport ("github.com/gin-gonic/gin""net/http"
)func InitRouters(r *gin.Engine) {//使用路由分組api := r.Group("api")initCourse(api)
}func initCourse(group *gin.RouterGroup) {// 路由分組v1 := group.Group("/v1"){// /api/v1/course// 路徑攜帶參數(shù)v1.GET("/course/search/:id", course.Get)v1.POST("/course/add/:id", course.Add)v1.PUT("/course/edit/:id", course.Edit)v1.DELETE("/course/del", course.Delete)}
}// 模型綁定, gin 引用了 validator,有一些預(yù)置標(biāo)簽
type course struct {Name string `json:"name" form:"name" binding:"required"`Teacher string `json:"teacher" form:"teacher" binding:"required"`Duration int `json:"duration" form:"duration" binding:"number"`
}func Add(c *gin.Context) {req := &course{}// 從form表單去綁定 c.Bind() c.ShouldBind()// 從json里去取值 c.BindJSON()// 帶should的bind 可以去返回錯(cuò)誤,不帶的會(huì)直接響應(yīng)請(qǐng)求err := c.ShouldBindJSON(req)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error(),})return}c.JSON(http.StatusOK, req)
}func Get(c *gin.Context) {// 獲取路徑上的參數(shù)id := c.Param("id")// 都是gin.context作為入?yún)?/span>c.JSON(http.StatusOK, gin.H{"method": c.Request.Method,"path": c.Request.URL.Path,"id": id,})
}func Edit(c *gin.Context) {req := &course{}err := c.ShouldBindJSON(req)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error(),})return}c.JSON(http.StatusOK, gin.H{"method": c.Request.Method,"path": c.Request.URL.Path,"req": req,})
}func Delete(c *gin.Context) {// 從queryString 獲取id := c.Query("id")// 都是gin.context作為入?yún)?/span>c.JSON(http.StatusOK, gin.H{"method": c.Request.Method,"path": c.Request.URL.Path,"id": id,})
}