gin: 接收参数时校验

一,安装第三方库:

$ go get -u github.com/go-playground/validator/v10
go: downloading github.com/go-playground/validator/v10 v10.24.0
go: downloading github.com/gabriel-vasile/mimetype v1.4.8
go: downloading golang.org/x/crypto v0.32.0
go: downloading golang.org/x/net v0.34.0
go: upgraded github.com/gabriel-vasile/mimetype v1.4.3 => v1.4.8
go: upgraded github.com/go-playground/validator/v10 v10.20.0 => v10.24.0
go: upgraded golang.org/x/crypto v0.23.0 => v0.32.0
go: upgraded golang.org/x/net v0.25.0 => v0.34.0
go: upgraded golang.org/x/sys v0.20.0 => v0.29.0
go: upgraded golang.org/x/text v0.15.0 => v0.21.0

 

二,校验get参数

代码:

//请求参数struct
type ImageListRequest struct {
	Cid        int  `form:"cid" json:"cid" binding:"required,gte=1,lte=100"`
	Category       string `form:"category" json:"category" binding:"required,min=2,max=10"`
}


//得到列表
func (ic *ImageController) List(c *gin.Context) {

	var req ImageListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}

	fmt.Println("cid:",req.Cid)
	fmt.Println("category:",req.Category)
	
	c.JSON(http.StatusOK, gin.H{
		"message": "image list",
	})
}

测试效果:参数不合法

参数合法

三,校验post参数

//请求参数struct
type ImageAddRequest struct {
	Cid        int  `form:"cid" json:"cid" binding:"required,gte=1,lte=100"`
	Title       string `form:"title" json:"title" binding:"required,min=2"`
}

//添加一条
func (ic *ImageController) Add(c *gin.Context) {

	var req ImageAddRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}

	fmt.Println("cid:",req.Cid)
	fmt.Println("title:",req.Title)
	
	//返回
	c.JSON(http.StatusOK, gin.H{
		"message": "image detail",
	})
}

 

测试效果:

合法时

posted @ 2025-01-31 15:02  刘宏缔的架构森林  阅读(41)  评论(0)    收藏  举报