package?main
import?(
???"github.com/gin-gonic/gin"
???"gopkg.in/go-playground/validator.v9"
???"net/http"
???"time"
)
type?Booking?struct?{
???CheckIn?time.Time?`form:"check_in"?validate:"required,bookableDate"?time_format:"2006-01-02"`
???CheckOut?time.Time?`form:"check_out"?validate:"required,gtfield=CheckIn"?time_format:"2006-01-02"`
}
func?main(){
???r?:=?gin.Default()
???validate?:=?validator.New()
???validate.RegisterValidation("bookableDate",?bookableDate)
???r.GET("/bookable",?func(c?*gin.Context)?{
??????var?book?Booking
??????if?err?:=?c.ShouldBind(&book);?err?!=?nil?{
?????????c.JSON(http.StatusInternalServerError,?gin.H{
????????????"error":?err.Error(),
?????????})
?????????c.Abort()
?????????return
??????}
??????if?err?:=?validate.Struct(book);?err?!=?nil?{
?????????c.JSON(http.StatusInternalServerError,?gin.H{
????????????"error":?err.Error(),
?????????})
?????????c.Abort()
?????????return
??????}
??????c.JSON(http.StatusOK,?gin.H{
?????????"message":?"OK",
?????????"booking":?book,
??????})
???})
???r.Run()
}
func?bookableDate(fl?validator.FieldLevel)?bool?{
???if?date,?ok?:=?fl.Field().Interface().(time.Time);?ok?{
??????today?:=?time.Now()
??????if?date.Unix()?>?today.Unix()?{
?????????return?true
??????}
???}
???return?false
}
2019-12-09
對的,V9就是這樣用的
2020-05-25
{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookableDate' tag"}w
2020-04-04
Undefined validation function 'bookableDate' on field 'CheckIn'
2020-03-31
為啥我的代碼 此處傳過來的時間恒為?2012-04-01 00:00:00 +0800 CST