Senior
Where should business validation (e.g., date checks, booking limit of 10 days) be located? In the handler or in the service?
sobes.tech AI
Answer from AI
Business validation, such as checking dates or limiting bookings to 10 days, should be in the service layer, not in the handler. The handler is responsible for receiving and passing data, handling HTTP requests, while the service handles business logic and rules. This allows for centralizing business rules, simplifying testing, and reusing logic.
Example:
func (s *BookingService) CreateBooking(req BookingRequest) error {
if req.EndDate.Sub(req.StartDate).Hours()/24 > 10 {
return errors.New("booking cannot exceed 10 days")
}
// other business logic
return s.repo.Save(req)
}
// In the handler, simply call the service
func (h *Handler) CreateBookingHandler(w http.ResponseWriter, r *http.Request) {
var req BookingRequest
// parse request
err := h.service.CreateBooking(req)
if err != nil {
// handle error
}
}