路由注冊
route := gin.Default()
//注冊驗證模版
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("bookabledate", bookableDate)
}
route.GET("/bookable", getBookable)
route.Run(":8085")
注冊驗證規(guī)則
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
}
定義接受結(jié)構(gòu)體
type Booking struct {
CheckIn string `form:"check_in" binding:"required,bookabledate"`
CheckOut string `form:"check_out" binding:"required,bookabledate"`
}
控制器參數(shù)綁定
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()})
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。