-
Notifications
You must be signed in to change notification settings - Fork 0
/
book.go
83 lines (69 loc) · 2.08 KB
/
book.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type Book struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Author string `json:"author"`
}
type CreateBookBody struct {
Name string `json:"name"`
Description string `json:"description"`
Author string `json:"author"`
}
func create(w http.ResponseWriter, r *http.Request) {
var body CreateBookBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
log.Printf("error decoding request body into CreateBookBody struct %v", err)
return
}
if err := DB.QueryRow("INSERT INTO books (name, description) VALUES ($1, $2)", body.Name, body.Description).Err(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error inserting book into books table %v", err)
return
}
w.WriteHeader(http.StatusCreated)
}
func getAll(w http.ResponseWriter, _ *http.Request) {
var books []Book
if err := DB.Select(&books, "SELECT id, name, description FROM books;"); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error querying books table %v", err)
return
}
j, err := json.Marshal(books)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error marshalling books into json %v", err)
return
}
w.Write(j)
}
func get(w http.ResponseWriter, r *http.Request) {
bookID, err := strconv.Atoi(chi.URLParam(r, "bookID"))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error parsing %d from string into integer %v", bookID, err)
return
}
var book Book
if err := DB.Get(&book, "SELECT id, name, description FROM books WHERE id = $1;", bookID); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error querying book from books table with id %d %v", bookID, err)
return
}
j, err := json.Marshal(book)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error marshalling books into json %v", err)
return
}
w.Write(j)
}