diff --git a/backend/handlers.go b/backend/handlers.go index f8bc143..8a07269 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -6,6 +6,9 @@ import ( "context" "encoding/json" "net/http" + "strconv" + + "github.com/go-chi/chi/v5" ) // GET /quotes @@ -56,16 +59,33 @@ func createQuote(w http.ResponseWriter, r *http.Request) { // DELETE /quotes func deleteQuote(w http.ResponseWriter, r *http.Request) { - var q Quote - err := json.NewDecoder(r.Body).Decode(&q) + // get id from URL + idParam := chi.URLParam(r, "id") + + // convert string → int + id, err := strconv.Atoi(idParam) if err != nil { - http.Error(w, "Invalid JSON", 400) + http.Error(w, "Invalid ID", http.StatusBadRequest) return } - err = db.QueryRow( + // execute delete + commandTag, err := db.Exec( context.Background(), - "DELETE FROM hlaskovnik WHERE id = $1 RETURNING *;", - q.Id, - ).Scan(&q.Id) + "DELETE FROM quotes WHERE id=$1", + id, + ) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + // check if anything was deleted + if commandTag.RowsAffected() == 0 { + http.Error(w, "Quote not found", http.StatusNotFound) + return + } + + // success response + w.WriteHeader(http.StatusNoContent) // 204 } diff --git a/backend/main.go b/backend/main.go index 178abc9..4063c3f 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.Delete("/quotes/{id}", deleteQuote) port := os.Getenv("PORT") if port == "" {