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" "context"
"encoding/json" "encoding/json"
"net/http" "net/http"
"strconv"
"github.com/go-chi/chi/v5"
) )
// GET /quotes // GET /quotes
@@ -56,16 +59,33 @@ func createQuote(w http.ResponseWriter, r *http.Request) {
// DELETE /quotes // DELETE /quotes
func deleteQuote(w http.ResponseWriter, r *http.Request) { func deleteQuote(w http.ResponseWriter, r *http.Request) {
var q Quote // get id from URL
err := json.NewDecoder(r.Body).Decode(&q) idParam := chi.URLParam(r, "id")
// convert string → int
id, err := strconv.Atoi(idParam)
if err != nil { if err != nil {
http.Error(w, "Invalid JSON", 400) http.Error(w, "Invalid ID", http.StatusBadRequest)
return return
} }
err = db.QueryRow( // execute delete
commandTag, err := db.Exec(
context.Background(), context.Background(),
"DELETE FROM hlaskovnik WHERE id = $1 RETURNING *;", "DELETE FROM quotes WHERE id=$1",
q.Id, id,
).Scan(&q.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 // routes
r.Get("/quotes", getQuotes) r.Get("/quotes", getQuotes)
r.Post("/quotes", createQuote) r.Post("/quotes", createQuote)
r.Delete("/quotes/{id}", deleteQuote)
port := os.Getenv("PORT") port := os.Getenv("PORT")
if port == "" { if port == "" {