1. 自定义验证

    1. import (
    2. "net/http"
    3. "reflect"
    4. "time"
    5. "github.com/gin-gonic/gin"
    6. "github.com/gin-gonic/gin/binding"
    7. "gopkg.in/go-playground/validator.v8"
    8. )
    9. // Booking contains binded and validated data.
    10. type Booking struct {
    11. //定义一个预约的时间大于今天的时间
    12. CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
    13. //gtfield=CheckIn退出的时间大于预约的时间
    14. CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
    15. func bookableDate(
    16. v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
    17. field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
    18. ) bool {
    19. //field.Interface().(time.Time)获取参数值并且转换为时间格式
    20. if date, ok := field.Interface().(time.Time); ok {
    21. today := time.Now()
    22. if today.Unix() > date.Unix() {
    23. return false
    24. }
    25. }
    26. return true
    27. }
    28. func main() {
    29. route := gin.Default()
    30. //注册验证
    31. v.RegisterValidation("bookabledate", bookableDate)
    32. }
    33. route.GET("/5lmh", getBookable)
    34. route.Run()
    35. }
    36. func getBookable(c *gin.Context) {
    37. var b Booking
    38. if err := c.ShouldBindWith(&b, binding.Query); err == nil {
    39. c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
    40. } else {
    41. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    42. }
    43. }
    44. // curl -X GET "http://localhost:8080/5lmh?check_in=2019-11-07&check_out=2019-11-20"