Files
hlaskovnik-reimagined/backend/handlers.go
T
2026-04-22 19:45:24 +02:00

136 lines
2.6 KiB
Go
Executable File

// TODO: READ AND UNDERSTAND
package main
import (
"context"
"encoding/json"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
// GET /quotes
func getQuotes(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(context.Background(), "SELECT * FROM hlaskovnik;")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer rows.Close()
var quotes []Quote
for rows.Next() {
var q Quote
rows.Scan(&q.Id, &q.Author, &q.Body)
quotes = append(quotes, q)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(quotes)
}
// POST /quotes
func createQuote(w http.ResponseWriter, r *http.Request) {
var q Quote
err := json.NewDecoder(r.Body).Decode(&q)
if err != nil {
http.Error(w, "Invalid JSON", 400)
return
}
err = db.QueryRow(
context.Background(),
"INSERT INTO hlaskovnik(author, body) VALUES($1, $2) RETURNING id;",
q.Author, q.Body,
).Scan(&q.Id)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(q)
}
// 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")
// convert string → int
id, err := strconv.Atoi(idParam)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
// execute delete
commandTag, err := db.Exec(
context.Background(),
"DELETE FROM hlaskovnik 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
}