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"
)
// GET /users
func getUsers(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(context.Background(), "SELECT id, name FROM users")
// GET /quotes
func getQuotes(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(context.Background(), "SELECT * FROM quotes")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer rows.Close()
var users []User
var quotes []Quote
for rows.Next() {
var u User
rows.Scan(&u.ID, &u.Name)
users = append(users, u)
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(users)
json.NewEncoder(w).Encode(quotes)
}
// POST /users
func createUser(w http.ResponseWriter, r *http.Request) {
var u User
// POST /quotes
func createQuote(w http.ResponseWriter, r *http.Request) {
var q Quote
err := json.NewDecoder(r.Body).Decode(&u)
err := json.NewDecoder(r.Body).Decode(&q)
if err != nil {
http.Error(w, "Invalid JSON", 400)
return
@@ -41,9 +41,9 @@ func createUser(w http.ResponseWriter, r *http.Request) {
err = db.QueryRow(
context.Background(),
"INSERT INTO users(name) VALUES($1) RETURNING id",
u.Name,
).Scan(&u.ID)
"INSERT INTO quotes(author, body) VALUES($1, $2) RETURNING id",
q.Author, q.Body,
).Scan(&q.Id)
if err != nil {
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")
json.NewEncoder(w).Encode(u)
json.NewEncoder(w).Encode(q)
}
+2 -2
View File
@@ -15,8 +15,8 @@ func main() {
r := chi.NewRouter()
// routes
r.Get("/users", getUsers)
r.Post("/users", createUser)
r.Get("/quotes", getQuotes)
r.Post("/quotes", createQuote)
port := os.Getenv("PORT")
if port == "" {