server.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package main
  2. import (
  3. "net/http"
  4. "reflect"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gin-gonic/gin/binding"
  8. "gopkg.in/go-playground/validator.v8"
  9. )
  10. type Booking struct {
  11. CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
  12. CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
  13. }
  14. func bookableDate(
  15. v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
  16. field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
  17. ) bool {
  18. if date, ok := field.Interface().(time.Time); ok {
  19. today := time.Now()
  20. if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
  21. return false
  22. }
  23. }
  24. return true
  25. }
  26. func main() {
  27. route := gin.Default()
  28. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  29. v.RegisterValidation("bookabledate", bookableDate)
  30. }
  31. route.GET("/bookable", getBookable)
  32. route.Run(":8085")
  33. }
  34. func getBookable(c *gin.Context) {
  35. var b Booking
  36. if err := c.ShouldBindWith(&b, binding.Query); err == nil {
  37. c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  38. } else {
  39. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  40. }
  41. }