1. 程式人生 > 其它 >gin中如何自定義驗證器

gin中如何自定義驗證器

package main

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

type Booking struct {
	// 包含繫結和驗證的資料,bookabledate就是自定義的驗證函式
	CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
	// gtfield=CheckIn只對數字或時間有效,參考官網連結
	// https://pkg.go.dev/github.com/go-playground/validator/v10#section-readme
	CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn,bookabledate" time_format:"2006-01-02"`
}

// 自定義驗證器
var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
	if date, ok := fl.Field().Interface().(time.Time); ok {
		today := time.Now()
		if today.After(date) {  // 輸入的日期必須大於今天的日期,否則驗證失敗
			return false
		}
	}
	return true
}

func main() {
	router := gin.Default()

	// 註冊驗證器
	validate, ok := binding.Validator.Engine().(*validator.Validate)
	if ok {
		validate.RegisterValidation("bookabledate", bookableDate)
	}

	router.GET("/bookable", getBookable)
	router.Run()
}

func getBookable(context *gin.Context) {
	var book Booking
	if err := context.ShouldBindWith(&book, binding.Query); err == nil {
		context.JSON(200, gin.H{"message": "book date is valid"})
	} else {
		context.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
	}
}