basic online
This commit is contained in:
68
internal/handler/budget.go
Normal file
68
internal/handler/budget.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"Engine/internal/model"
|
||||
"Engine/internal/service"
|
||||
)
|
||||
|
||||
type BudgetHandler struct {
|
||||
svc *service.BudgetService
|
||||
}
|
||||
|
||||
func NewBudgetHandler(svc *service.BudgetService) *BudgetHandler {
|
||||
return &BudgetHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *BudgetHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req model.CreateBudgetRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
budget, err := h.svc.Create(r.Context(), req)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, budget)
|
||||
}
|
||||
|
||||
func (h *BudgetHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.Atoi(r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Amount float64 `json:"amount"`
|
||||
Notes string `json:"notes"`
|
||||
ChangedBy string `json:"changed_by"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
budget, err := h.svc.Update(r.Context(), id, body.Amount, body.Notes, body.ChangedBy)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, budget)
|
||||
}
|
||||
|
||||
func (h *BudgetHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.Atoi(r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
if err := h.svc.Delete(r.Context(), id); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
Reference in New Issue
Block a user