add delete quote method
This commit is contained in:
+27
-7
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 == "" {
|
||||
|
||||
Reference in New Issue
Block a user