|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + "github.com/asaskevich/govalidator" |
| 9 | + "github.com/go-chi/chi/v5" |
| 10 | + "github.com/semmidev/problem" |
| 11 | +) |
| 12 | + |
| 13 | +type KanbanHandler struct { |
| 14 | + service Service |
| 15 | +} |
| 16 | + |
| 17 | +func NewHandler(service Service) *KanbanHandler { |
| 18 | + return &KanbanHandler{service: service} |
| 19 | +} |
| 20 | + |
| 21 | +// mapErrorToProblem is the central place where domain errors and infrastructure errors |
| 22 | +// are translated into RFC 7807 Problem Details. |
| 23 | +func mapErrorToProblem(err error) *problem.Problem { |
| 24 | + // 1. Not Found Domain Error |
| 25 | + if errors.Is(err, ErrTaskNotFound) { |
| 26 | + return problem.Wrap(err, problem.NotFound, problem.WithDetail(err.Error())) |
| 27 | + } |
| 28 | + // 2. Business Logic Validation Errors |
| 29 | + if errors.Is(err, ErrInvalidStatus) || errors.Is(err, ErrTitleCannotBeEmpty) { |
| 30 | + return problem.Wrap(err, problem.UnprocessableEntity, problem.WithDetail(err.Error())) |
| 31 | + } |
| 32 | + |
| 33 | + // 3. Fallback to 500 Internal Server error for anything unhandled |
| 34 | + // In a real app we'd log the original err securely here and mask details to the client |
| 35 | + return problem.Wrap(err, problem.InternalServerError, problem.WithDetail("An unexpected internal error occurred.")) |
| 36 | +} |
| 37 | + |
| 38 | +// writeError Helper |
| 39 | +func writeError(w http.ResponseWriter, r *http.Request, err error) { |
| 40 | + p := mapErrorToProblem(err) |
| 41 | + // Optionally attach instance URI |
| 42 | + p.Instance = r.URL.Path |
| 43 | + p.Write(w) |
| 44 | +} |
| 45 | + |
| 46 | +// ==== Request Models ==== |
| 47 | + |
| 48 | +type CreateTaskRequest struct { |
| 49 | + Title string `json:"title" valid:"required,stringlength(3|100)"` |
| 50 | + Description string `json:"description" valid:"type(string)"` |
| 51 | +} |
| 52 | + |
| 53 | +type MoveTaskRequest struct { |
| 54 | + Status string `json:"status" valid:"in(TODO|DOING|DONE),required"` |
| 55 | +} |
| 56 | + |
| 57 | +// ==== HTTP Handlers ==== |
| 58 | + |
| 59 | +func (h *KanbanHandler) CreateTask(w http.ResponseWriter, r *http.Request) { |
| 60 | + var req CreateTaskRequest |
| 61 | + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 62 | + problem.Wrap(err, problem.BadRequest, problem.WithDetail("Invalid or malformed JSON payload")).Write(w) |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + if _, err := govalidator.ValidateStruct(req); err != nil { |
| 67 | + var validationErrors []map[string]string |
| 68 | + if errs, ok := err.(govalidator.Errors); ok { |
| 69 | + for _, e := range errs { |
| 70 | + if valErr, isValErr := e.(govalidator.Error); isValErr { |
| 71 | + validationErrors = append(validationErrors, map[string]string{ |
| 72 | + "field": valErr.Name, |
| 73 | + "message": valErr.Err.Error(), |
| 74 | + }) |
| 75 | + } else { |
| 76 | + validationErrors = append(validationErrors, map[string]string{"message": e.Error()}) |
| 77 | + } |
| 78 | + } |
| 79 | + } else { |
| 80 | + validationErrors = append(validationErrors, map[string]string{"message": err.Error()}) |
| 81 | + } |
| 82 | + |
| 83 | + p := problem.New( |
| 84 | + problem.UnprocessableEntity, |
| 85 | + problem.WithDetail("request parameters failed validation"), |
| 86 | + problem.WithInstance(r.URL.Path), |
| 87 | + problem.WithExtension("invalid_params", validationErrors), |
| 88 | + ) |
| 89 | + p.Write(w) |
| 90 | + return |
| 91 | + } |
| 92 | + |
| 93 | + task, err := h.service.CreateTask(req.Title, req.Description) |
| 94 | + if err != nil { |
| 95 | + writeError(w, r, err) |
| 96 | + return |
| 97 | + } |
| 98 | + |
| 99 | + w.Header().Set("Content-Type", "application/json") |
| 100 | + w.WriteHeader(http.StatusCreated) |
| 101 | + json.NewEncoder(w).Encode(task) |
| 102 | +} |
| 103 | + |
| 104 | +func (h *KanbanHandler) GetTask(w http.ResponseWriter, r *http.Request) { |
| 105 | + id := chi.URLParam(r, "id") |
| 106 | + task, err := h.service.GetTask(id) |
| 107 | + if err != nil { |
| 108 | + writeError(w, r, err) |
| 109 | + return |
| 110 | + } |
| 111 | + |
| 112 | + w.Header().Set("Content-Type", "application/json") |
| 113 | + json.NewEncoder(w).Encode(task) |
| 114 | +} |
| 115 | + |
| 116 | +func (h *KanbanHandler) MoveTask(w http.ResponseWriter, r *http.Request) { |
| 117 | + id := chi.URLParam(r, "id") |
| 118 | + |
| 119 | + var req MoveTaskRequest |
| 120 | + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 121 | + problem.Wrap(err, problem.BadRequest, problem.WithDetail("Invalid JSON")).Write(w) |
| 122 | + return |
| 123 | + } |
| 124 | + |
| 125 | + if _, err := govalidator.ValidateStruct(req); err != nil { |
| 126 | + var validationErrors []map[string]string |
| 127 | + if errs, ok := err.(govalidator.Errors); ok { |
| 128 | + for _, e := range errs { |
| 129 | + if valErr, isValErr := e.(govalidator.Error); isValErr { |
| 130 | + validationErrors = append(validationErrors, map[string]string{ |
| 131 | + "field": valErr.Name, |
| 132 | + "message": valErr.Err.Error(), |
| 133 | + }) |
| 134 | + } else { |
| 135 | + validationErrors = append(validationErrors, map[string]string{"message": e.Error()}) |
| 136 | + } |
| 137 | + } |
| 138 | + } else { |
| 139 | + validationErrors = append(validationErrors, map[string]string{"message": err.Error()}) |
| 140 | + } |
| 141 | + |
| 142 | + p := problem.New( |
| 143 | + problem.UnprocessableEntity, |
| 144 | + problem.WithDetail("validation failed for status update"), |
| 145 | + problem.WithExtension("invalid_params", validationErrors), |
| 146 | + ) |
| 147 | + p.Write(w) |
| 148 | + return |
| 149 | + } |
| 150 | + |
| 151 | + task, err := h.service.MoveTask(id, req.Status) |
| 152 | + if err != nil { |
| 153 | + writeError(w, r, err) |
| 154 | + return |
| 155 | + } |
| 156 | + |
| 157 | + w.Header().Set("Content-Type", "application/json") |
| 158 | + json.NewEncoder(w).Encode(task) |
| 159 | +} |
| 160 | + |
| 161 | +func (h *KanbanHandler) ListTasks(w http.ResponseWriter, r *http.Request) { |
| 162 | + tasks, err := h.service.ListTasks() |
| 163 | + if err != nil { |
| 164 | + writeError(w, r, err) |
| 165 | + return |
| 166 | + } |
| 167 | + |
| 168 | + w.Header().Set("Content-Type", "application/json") |
| 169 | + json.NewEncoder(w).Encode(tasks) |
| 170 | +} |
0 commit comments