add delete quote method

This commit is contained in:
Odweta
2026-03-19 11:59:19 +01:00
parent 8e27f0a5c2
commit 205bd79cdf
2 changed files with 28 additions and 7 deletions
+27 -7
View File
@@ -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
}
+1
View File
@@ -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 == "" {