server.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // Booking contains binded and validated data.
  11. type Booking struct {
  12. CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
  13. CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
  14. }
  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. if date, ok := field.Interface().(time.Time); ok {
  20. today := time.Now()
  21. if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
  22. return false
  23. }
  24. }
  25. return true
  26. }
  27. func main() {
  28. route := gin.Default()
  29. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  30. v.RegisterValidation("bookabledate", bookableDate)
  31. }
  32. route.GET("/bookable", getBookable)
  33. route.Run(":8085")
  34. }
  35. func getBookable(c *gin.Context) {
  36. var b Booking
  37. if err := c.ShouldBindWith(&b, binding.Query); err == nil {
  38. c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  39. } else {
  40. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  41. }
  42. }