/
main.go
186 lines (155 loc) · 4.77 KB
/
main.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"goji.io"
"goji.io/pat"
)
func ErrorWithJSON(w http.ResponseWriter, message string, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
fmt.Fprintf(w, "{message: %q}", message)
}
func ResponseWithJSON(w http.ResponseWriter, json []byte, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
w.Write(json)
}
type Book struct {
ISBN string `json:"isbn" bson:"isbn,omitempty"`
Title string `json:"title" bson:"title,omitempty"`
Authors []string `json:"authors" bson:"authors,omitempty"`
Price string `json:"price" bson:"price,omitempty"`
}
func main() {
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://172.19.0.2"))
if err != nil {
panic(err)
}
defer func() {
if err := client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
mux := goji.NewMux()
mux.HandleFunc(pat.Get("/books"), allBooks(client))
mux.HandleFunc(pat.Post("/books"), addBook(client))
mux.HandleFunc(pat.Get("/books/:isbn"), bookByISBN(client))
mux.HandleFunc(pat.Put("/books/:isbn"), updateBook(client))
mux.HandleFunc(pat.Delete("/books/:isbn"), deleteBook(client))
http.ListenAndServe("localhost:8080", mux)
}
func allBooks(c *mongo.Client) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
coll := c.Database("store").Collection("books")
cursor, err := coll.Find(context.TODO(), bson.M{})
if err != nil {
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed get all books: ", err)
return
}
var books []Book
err = cursor.All(context.TODO(), &books)
if err != nil {
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed get all books: ", err)
return
}
respBody, err := json.MarshalIndent(books, "", " ")
if err != nil {
log.Fatal(err)
}
ResponseWithJSON(w, respBody, http.StatusOK)
}
}
func addBook(c *mongo.Client) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var book Book
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&book)
if err != nil {
ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest)
return
}
coll := c.Database("store").Collection("books")
_, err = coll.InsertOne(context.TODO(), book)
if err != nil {
// FIXME: Check for duplicate document
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed insert book: ", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Location", r.URL.Path+"/"+book.ISBN)
w.WriteHeader(http.StatusCreated)
}
}
func bookByISBN(c *mongo.Client) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
isbn := pat.Param(r, "isbn")
coll := c.Database("store").Collection("books")
var book Book
err := coll.FindOne(context.TODO(), bson.M{"isbn": isbn}).Decode(&book)
if err != nil {
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed find book: ", err)
return
}
if book.ISBN == "" {
ErrorWithJSON(w, "Book not found", http.StatusNotFound)
return
}
respBody, err := json.MarshalIndent(book, "", " ")
if err != nil {
log.Fatal(err)
}
ResponseWithJSON(w, respBody, http.StatusOK)
}
}
func updateBook(c *mongo.Client) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
isbn := pat.Param(r, "isbn")
var book Book
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&book)
if err != nil {
ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest)
return
}
coll := c.Database("store").Collection("books")
filter := bson.M{"isbn": isbn}
update := bson.D{{"$set", book}}
_, err = coll.UpdateOne(context.TODO(), filter, update)
if err != nil {
switch err {
default:
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed update book: ", err)
return
}
}
}
}
func deleteBook(c *mongo.Client) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
isbn := pat.Param(r, "isbn")
coll := c.Database("store").Collection("books")
filter := bson.M{"isbn": isbn}
_, err := coll.DeleteOne(context.TODO(), filter)
if err != nil {
switch err {
default:
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed delete book: ", err)
return
}
}
w.WriteHeader(http.StatusNoContent)
}
}