add 'update' (PUT) quote method
This commit is contained in:
+45
-1
@@ -57,7 +57,51 @@ func createQuote(w http.ResponseWriter, r *http.Request) {
|
||||
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) {
|
||||
// get id from URL
|
||||
idParam := chi.URLParam(r, "id")
|
||||
|
||||
@@ -17,6 +17,7 @@ func main() {
|
||||
// routes
|
||||
r.Get("/quotes", getQuotes)
|
||||
r.Post("/quotes", createQuote)
|
||||
r.Put("/quotes/{id}", updateQuote)
|
||||
r.Delete("/quotes/{id}", deleteQuote)
|
||||
|
||||
port := os.Getenv("PORT")
|
||||
|
||||
Reference in New Issue
Block a user