books := &books{}
router.Handle("/books", books).Methods("GET")
+ router.HandleFunc("/books", books.add).Methods("POST")
return logIncoming(router)
}
@@ -43,6 +44,17 @@ type book struct {
Title string `json:"title"`
}
+func (h *books) add(w http.ResponseWriter, r *http.Request) {
+ var newBook book
+ err := json.NewDecoder(r.Body).Decode(&newBook)
+ if err != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ h.all = append(h.all, newBook)
+ w.WriteHeader(http.StatusCreated)
+}
+
func (h *books) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
model := struct {
And with that change we end this tutorial. By now you
should have pretty good understanding on how routing, logging
and minimal error handling works for HTTP API
implementations. There is of course a lot more to learn once you
start involving database storage, concurrency and things like
authentication and access control. But that is for another
tutorial.
The End