一,代码
1,global/validator.go
package globalimport "github.com/go-playground/validator/v10"//存放GetMessages()方法
type Validator interface {GetMessages() ValidatorMessages
}//校验信息
type ValidatorMessages map[string]string// GetErrorMsg方法, 获取错误信息
func GetErrorMsg(request interface{}, err error) string {if _, isValidatorErrors := err.(validator.ValidationErrors); isValidatorErrors {_, isValidator := request.(Validator)for _, v := range err.(validator.ValidationErrors) {// 若 request 结构体实现 Validator 接口即可实现自定义错误信息if isValidator {if message, exist := request.(Validator).GetMessages()[v.Field() + "." + v.Tag()]; exist {return message}}return v.Error()}}return "Parameter error"
}
2,request/Image.og
package requestimport ("imagebank/global"
)//ImageList请求参数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 (request ImageListRequest) GetMessages() global.ValidatorMessages {return global.ValidatorMessages{"Cid.required": "cid不能为空","Cid.gte": "cid不能小于1","Cid.lte": "cid不能大于100","Category.required": "类型不能为空","Category.min": "类型最少2个字符","Category.max": "类型最多10个字符",}
}
3,controller/ImageController.go
//得到列表
func (ic *ImageController) List(c *gin.Context) {var req request.ImageListRequestif err := c.ShouldBindQuery(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"err": global.GetErrorMsg(req, err),})return}fmt.Println("cid:",req.Cid)fmt.Println("category:",req.Category)c.JSON(http.StatusOK, gin.H{"message": "image list",})
}
二,测试效果