Skip to content
Permalink
Browse files

Add loggingMiddleware

  • Loading branch information...
shibayu36 committed Jun 2, 2019
1 parent a230d9e commit 93c2a99e4fbcc3828d823dd8935a55c1c64e79ff
Showing with 39 additions and 1 deletion.
  1. +24 −0 web/middleware.go
  2. +15 −1 web/server.go
@@ -1,9 +1,33 @@
package web

import (
"log"
"net/http"
"time"
)

type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
}

func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}

func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := &loggingResponseWriter{w, http.StatusOK}
next.ServeHTTP(lrw, r)
log.Printf("%s %s took %.2fmsec and returned %d %s", r.Method, r.URL.Path,
float64(time.Now().Sub(start).Nanoseconds())/1e6,
lrw.statusCode, http.StatusText(lrw.statusCode),
)
})
}

func headerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-XSS-Protection", "1; mode=block")
@@ -3,6 +3,8 @@ package web
//go:generate go-assets-builder --package=web --output=./templates-gen.go --strip-prefix="/templates/" --variable=Templates ../templates

import (
"fmt"
"html"
"net/http"

"github.com/dimfeld/httptreemux"
@@ -28,11 +30,23 @@ type server struct {
func (s *server) Handler() http.Handler {
router := httptreemux.New()

// ...
handle := func(method, path string, handler http.Handler) {
router.UsingContext().Handler(method, path,
csrfMiddleware(loggingMiddleware(headerMiddleware(handler))),
)
}

handle("GET", "/", s.indexHandler())

return router
}

func (s *server) indexHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
}

var csrfMiddleware = func(next http.Handler) http.Handler {
return nosurf.New(next)
}

0 comments on commit 93c2a99

Please sign in to comment.
You can’t perform that action at this time.