package main
import (
"fmt"
"github.com/go-playground/validator/v10"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// Booking contains binded and validated data.
type Booking struct {
CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
}
//validator v9以上寫法
func bookableDate(fl validator.FieldLevel) bool {
if date,ok:=fl.Field().Interface().(time.Time);ok{
today:=time.Now()
fmt.Println("date:",date)
if date.Unix()>today.Unix(){
fmt.Println("date unix :",date.Unix())
return true
}
}
return false
}
//validator v8寫法
//func bookableDate(
// v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
// field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
//) bool {
// if date, ok := field.Interface().(time.Time); ok {
// today := time.Now()
// if date.Unix()>today.Unix(){
// return true
// }
// }
// return false
//}
func main() {
route := gin.Default()
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("bookabledate", bookableDate)
}
route.GET("/bookable", getBookable)
route.Run()
}
func getBookable(c *gin.Context) {
var b Booking
if err := c.ShouldBindWith(&b, binding.Query); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusOK,gin.H{"message":"ok","booking":b})
}
}
運(yùn)行后酸舍,模擬請(qǐng)求
1.正確參數(shù)結(jié)果
curl -X GET "http://localhost:8080/bookable?check_in=2020-07-29&check_out=2020-07-30"
{"booking":{"CheckIn":"2020-07-29T00:00:00+08:00","CheckOut":"2020-07-30T00:00:00+08:00"},"message":"ok"}%
2.非法參數(shù)(check_in時(shí)間小于當(dāng)前時(shí)間2020-07-09)結(jié)果
curl -X GET "http://localhost:8080/bookable?check_in=2020-07-01&check_out=2020-07-30"
{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%
補(bǔ)充
需要注意的是 Tag字段中 逗號(hào) 前后不能有空格帅韧,不然會(huì)報(bào)錯(cuò)...