From 4d5f6483137f6db96a5708369e07626907ed86e0 Mon Sep 17 00:00:00 2001 From: Odweta Date: Thu, 19 Mar 2026 12:19:09 +0100 Subject: [PATCH] add 'update' (PUT) quote method --- backend/handlers.go | 46 ++++++++++++++++++++++++++++++++++++++++++++- backend/main.go | 1 + 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/backend/handlers.go b/backend/handlers.go index 513503d..edd1b69 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -57,7 +57,51 @@ func createQuote(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(q) } -// DELETE /quotes +// PUT /quotes/{id} +func updateQuote(w http.ResponseWriter, r *http.Request) { + // get ID from URL + idParam := chi.URLParam(r, "id") + id, err := strconv.Atoi(idParam) + if err != nil { + http.Error(w, "Invalid ID", http.StatusBadRequest) + return + } + + // parse request body + var q Quote + err = json.NewDecoder(r.Body).Decode(&q) + if err != nil { + http.Error(w, "Invalid JSON", http.StatusBadRequest) + return + } + + // update DB + commandTag, err := db.Exec( + context.Background(), + `UPDATE hlaskovnik + SET author=$1, body=$2 + WHERE id=$3`, + q.Author, q.Body, id, + ) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + // check if row exists + if commandTag.RowsAffected() == 0 { + http.Error(w, "Quote not found", http.StatusNotFound) + return + } + + // return updated object + q.ID = id + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(q) +} + +// DELETE /quotes{id} func deleteQuote(w http.ResponseWriter, r *http.Request) { // get id from URL idParam := chi.URLParam(r, "id") diff --git a/backend/main.go b/backend/main.go index 4063c3f..68ffb2f 100644 --- a/backend/main.go +++ b/backend/main.go @@ -17,6 +17,7 @@ func main() { // routes r.Get("/quotes", getQuotes) r.Post("/quotes", createQuote) + r.Put("/quotes/{id}", updateQuote) r.Delete("/quotes/{id}", deleteQuote) port := os.Getenv("PORT")