Skip to content

Commit

Permalink
ResponseWriter wrap to log status code.
Browse files Browse the repository at this point in the history
  • Loading branch information
oliverjanik committed Apr 2, 2014
1 parent 619ae22 commit 50dda8e
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions file-server.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,21 @@ import (
"os"
)

type loggingHandler struct {
h http.Handler
type loggingResponseWriter struct {
http.ResponseWriter
}

func (f *loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL)
f.h.ServeHTTP(w, r)
func (w *loggingResponseWriter) WriteHeader(code int) {
log.Printf("%d", code)
w.ResponseWriter.WriteHeader(code)
}

func wrapHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lw := &loggingResponseWriter{w}
log.Printf("%s %s", r.Method, r.URL)
handler.ServeHTTP(lw, r)
})
}

func main() {
Expand All @@ -22,13 +30,11 @@ func main() {
log.Fatal(err)
}

lh := &loggingHandler{http.FileServer(http.Dir(wd))}

port := 8001

log.Printf("Starting server on port %d", port)

addr := fmt.Sprintf(":%d", port)

log.Fatal(http.ListenAndServe(addr, lh))
log.Fatal(http.ListenAndServe(addr, wrapHandler(http.FileServer(http.Dir(wd)))))
}

0 comments on commit 50dda8e

Please sign in to comment.