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

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"net/http"
	"time"
)

// 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字段中 逗号 前后不能有空格,不然会报错...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值