路由注册
route := gin.Default()
//注册验证模版
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("bookabledate", bookableDate)
}
route.GET("/bookable", getBookable)
route.Run(":8085")
注册验证规则
func bookableDate(
v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
) bool {
fmt.Println(topStruct,currentStructOrField,field,fieldType,fieldKind,param)
if date, ok := field.Interface().(string); ok {
if date == "1" {
return false
}
}
return true
}
定义接受结构体
type Booking struct {
CheckIn string `form:"check_in" binding:"required,bookabledate"`
CheckOut string `form:"check_out" binding:"required,bookabledate"`
}
控制器参数绑定
func getBookable(c *gin.Context) {
var b Booking
if err := c.ShouldBindWith(&b, binding.Query); err == nil {
fmt.Println(b)
c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
}
}
网友评论