GIN 对传递的参数进行验证

先定义一个接受参数的结构体

type parmValid struct {
	Current int `form:"current"  binding:"required,PageValid"`
	Page_size int `form:"page_size"  binding:"required,PageValid"`
	Start_time time.Time `form:"start_time" binding:"required,TimeValid" time_format:"2006-01-02 15:04:05"`
	End_time time.Time `form:"end_time" binding:"required,TimeValid" time_format:"2006-01-02 15:04:05"`
	Merchant_id string `form:"merchant_id"  binding:"required,MerchantIdAndStoreIdValid"`
	Store_id string `form:"store_id"  binding:"required,MerchantIdAndStoreIdValid"`
}

binding中的required 表示必须传递的参数,PageValid为自定义的校验方法

func PageValid(
	v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
	field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
) bool {
	if num, ok := field.Interface().(int); ok {
		if num<=0 {
			return false
		}
	}
	return true
}

在路由这边注册验证器


func (ctrl *ReportFormController) Router(router *gin.Engine) {
	//r := router.Group("go/api/v1",middleware.Middle)
	r := router.Group("go/api/v1")
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("PageValid", webgo.PageValid)
		v.RegisterValidation("TimeValid", webgo.TimeValid)
		v.RegisterValidation("MerchantIdAndStoreIdValid", webgo.MerchantIdAndStoreIdValid)
	}
	r.GET("reportForm/store/:store_id", ctrl.getReportForm)
	r.GET("reportDevice/store/:store_id", ctrl.getReportDevice)
	r.GET("reportDevice/test", ctrl.test)
}

接受参数时绑定校验

if err := ctx.ShouldBindWith(&parmValid, binding.Query); err == nil {
        ......
}

 

你可能感兴趣的:(golang)