-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
55 lines (44 loc) · 1.36 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"errors"
"fmt"
"github.com/gofiber/fiber/v2"
"net/http"
)
const (
EndpointCreateReservation = "/v1/reservations"
EndpointGetReservation = "/v1/reservation/:id"
)
type Handler struct {
service Service
}
func NewHandler(service Service) *Handler {
return &Handler{service: service}
}
func (h *Handler) RegisterRoutes(app *fiber.App) {
app.Get(EndpointGetReservation, h.GetReservation)
app.Post(EndpointCreateReservation, h.CreateReservation)
}
func (h *Handler) GetReservation(ctx *fiber.Ctx) error {
return ctx.SendStatus(fiber.StatusNotImplemented)
}
func (h *Handler) CreateReservation(ctx *fiber.Ctx) error {
var reqBody ReqBody
if err := ctx.BodyParser(&reqBody); err != nil {
return ctx.Status(http.StatusBadRequest).SendString(err.Error())
}
if err := reqBody.Validate(); err != nil {
return ctx.Status(http.StatusBadRequest).SendString(err.Error())
}
if err := h.service.CreateReservation(ctx.Context(), reqBody.ToReservation()); err != nil {
switch {
case errors.Is(err, ErrNoEnoughCapacity):
return ctx.Status(http.StatusBadRequest).SendString("Not enough capacity")
default:
fmt.Println("[ERROR]", err.Error())
return ctx.Status(http.StatusInternalServerError).SendString("Please try again later")
}
}
ctx.Location("/v1/reservation/" + reqBody.ReservationID)
return ctx.SendStatus(http.StatusCreated)
}