Use more powerful router

Take a moment and think about the last change,.... will it scale for multiple handlers? If you think about it the method is part of the request and what we want is this handler never to be invoked unless the method is GET, that sound like a routing rule. However the muxer in package net/http does not support this out of the box. We have two options
  1. Implement a midleware that checks it for us and use that
  2. Or use another package with this capability
Hard choice right ;-). Let's use the package.
"net/http" "os" + + "" ) func main() { @@ -18,19 +20,15 @@ func main() { } } -func NewRouter() (router *http.ServeMux) { - router = http.NewServeMux() - router.Handle("/books", &books{}) +func NewRouter() (router *mux.Router) { + router = mux.NewRouter() + router.Handle("/books", &books{}).Methods("GET") return } type books struct{} func (h *books) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if r.Method != "GET" { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } w.Header().Set("Content-Type", "application/json") model := struct { Message string `json:"message"`
prev toc next