add 'update' (PUT) quote method

This commit is contained in:
Odweta
2026-03-19 12:19:09 +01:00
parent f4e986500d
commit 4d5f648313
2 changed files with 46 additions and 1 deletions
+45 -1
View File
@@ -57,7 +57,51 @@ func createQuote(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(q) 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) { func deleteQuote(w http.ResponseWriter, r *http.Request) {
// get id from URL // get id from URL
idParam := chi.URLParam(r, "id") idParam := chi.URLParam(r, "id")
+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.Put("/quotes/{id}", updateQuote)
r.Delete("/quotes/{id}", deleteQuote) r.Delete("/quotes/{id}", deleteQuote)
port := os.Getenv("PORT") port := os.Getenv("PORT")