Log requests

All requests to our handler need to be logged. This is where middlewares come in handly. Middlewares are simply put a routine that does something before or after (or both), another handler.
func NewRouter() (router *mux.Router) { router = mux.NewRouter() - router.Handle("/books", &books{}).Methods("GET") + router.Handle("/books", logIncoming(&books{})).Methods("GET") return } +func logIncoming(next http.Handler) http.HandlerFunc { + log := log.New(os.Stderr, "", log.LstdFlags) + return func(w http.ResponseWriter, r *http.Request) { + log.Printf("%s %s", r.Method, r.URL.Path) + next.ServeHTTP(w, r) + } +} + type books struct{} func (h *books) ServeHTTP(w http.ResponseWriter, r *http.Request) {
prev toc next