This commit is contained in:
Odweta
2026-03-19 10:57:37 +01:00
parent 4deb11fd06
commit 4d9cf01e1d
3 changed files with 18 additions and 18 deletions
Executable
BIN
View File
Binary file not shown.
+16 -16
View File
@@ -8,32 +8,32 @@ import (
"net/http" "net/http"
) )
// GET /users // GET /quotes
func getUsers(w http.ResponseWriter, r *http.Request) { func getQuotes(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(context.Background(), "SELECT id, name FROM users") rows, err := db.Query(context.Background(), "SELECT * FROM quotes")
if err != nil { if err != nil {
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
} }
defer rows.Close() defer rows.Close()
var users []User var quotes []Quote
for rows.Next() { for rows.Next() {
var u User var q Quote
rows.Scan(&u.ID, &u.Name) rows.Scan(&q.Id, &q.Author, &q.Body)
users = append(users, u) quotes = append(quotes, q)
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users) json.NewEncoder(w).Encode(quotes)
} }
// POST /users // POST /quotes
func createUser(w http.ResponseWriter, r *http.Request) { func createQuote(w http.ResponseWriter, r *http.Request) {
var u User var q Quote
err := json.NewDecoder(r.Body).Decode(&u) err := json.NewDecoder(r.Body).Decode(&q)
if err != nil { if err != nil {
http.Error(w, "Invalid JSON", 400) http.Error(w, "Invalid JSON", 400)
return return
@@ -41,9 +41,9 @@ func createUser(w http.ResponseWriter, r *http.Request) {
err = db.QueryRow( err = db.QueryRow(
context.Background(), context.Background(),
"INSERT INTO users(name) VALUES($1) RETURNING id", "INSERT INTO quotes(author, body) VALUES($1, $2) RETURNING id",
u.Name, q.Author, q.Body,
).Scan(&u.ID) ).Scan(&q.Id)
if err != nil { if err != nil {
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
@@ -51,5 +51,5 @@ func createUser(w http.ResponseWriter, r *http.Request) {
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(u) json.NewEncoder(w).Encode(q)
} }
+2 -2
View File
@@ -15,8 +15,8 @@ func main() {
r := chi.NewRouter() r := chi.NewRouter()
// routes // routes
r.Get("/users", getUsers) r.Get("/quotes", getQuotes)
r.Post("/users", createUser) r.Post("/quotes", createQuote)
port := os.Getenv("PORT") port := os.Getenv("PORT")
if port == "" { if port == "" {