Use proper middleware

This commit is contained in:
Lena Fuhrimann 2017-03-05 15:02:59 +01:00
parent 695ff278b6
commit c7d509f248
4 changed files with 38 additions and 27 deletions

View file

@ -7,17 +7,21 @@ import (
)
// Logger logs HTTP requests
func Logger(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
func Logger() Middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
defer func() {
log.Printf(
"%s\t%s\t%s",
r.Method,
r.RequestURI,
time.Since(start),
)
}()
log.Printf(
"%s\t%s\t%s",
r.Method,
r.RequestURI,
time.Since(start),
)
})
next(w, r)
}
}
}

14
middleware.go Normal file
View file

@ -0,0 +1,14 @@
package main
import "net/http"
// Middleware is an HTTP middleware
type Middleware func(http.HandlerFunc) http.HandlerFunc
// Chain applies middleware to an HTTP handler function
func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {
for i := len(middlewares) - 1; i >= 0; i-- {
f = middlewares[i](f)
}
return f
}

View file

@ -1,8 +1,6 @@
package main
import (
"net/http"
"github.com/gorilla/mux"
)
@ -11,15 +9,10 @@ func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler)
router.
Methods(route.Method).
Path(route.Pattern).
Handler(handler)
HandlerFunc(route.HandlerFunc)
}
return router

View file

@ -16,41 +16,41 @@ var routes = Routes{
Route{
"GET",
"/",
indexPageHandler,
Chain(indexPageHandler, Logger()),
},
Route{
"GET",
"/buckets",
bucketsPageHandler,
Chain(bucketsPageHandler, Logger()),
},
Route{
"GET",
"/buckets/{bucketName}",
bucketPageHandler,
Chain(bucketPageHandler, Logger()),
},
Route{
"POST",
"/api/buckets",
createBucketHandler,
Chain(createBucketHandler, Logger()),
},
Route{
"DELETE",
"/api/buckets/{bucketName}",
deleteBucketHandler,
Chain(deleteBucketHandler, Logger()),
},
Route{
"GET",
"/api/buckets/{bucketName}/objects/{objectName}",
getObjectHandler,
Chain(getObjectHandler, Logger()),
},
Route{
"POST",
"/api/buckets/{bucketName}/objects",
createObjectHandler,
Chain(createObjectHandler, Logger()),
},
Route{
"DELETE",
"/api/buckets/{bucketName}/objects/{objectName}",
deleteObjectHandler,
Chain(deleteObjectHandler, Logger()),
},
}