// TODO: READ AND UNDERSTAND package main import ( "context" "encoding/json" "net/http" ) // 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) } // DELETE /quotes func deleteQuote(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(), "DELETE FROM hlaskovnik WHERE id = $1 RETURNING *;", q.Id, ).Scan(&q.Id) }