「Go」Gin框架之validator v8升到v10的自定义验证器

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})
    }
}

运行后,模拟请求
1.正确参数结果

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.非法参数(check_in时间小于当前时间2020-07-09)结果

 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"}%

补充
需要注意的是 Tag字段中 逗号 前后不能有空格,不然会报错...

你可能感兴趣的:(「Go」Gin框架之validator v8升到v10的自定义验证器)