From a3a148b0ff29a0196649336ec5603cd3f2bce8cc Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Mon, 6 Jul 2015 22:48:54 +0200 Subject: [PATCH] Write access-log --- logResponseWriter.go | 40 ++++++++++++++++++++++++++++++++++++++++ main.go | 15 ++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 logResponseWriter.go diff --git a/logResponseWriter.go b/logResponseWriter.go new file mode 100644 index 0000000..ebbaca9 --- /dev/null +++ b/logResponseWriter.go @@ -0,0 +1,40 @@ +package main + +import "net/http" + +// LogResponseWriter wraps the standard http.ResponseWritter allowing for more +// verbose logging +type LogResponseWriter struct { + Status int + Size int + http.ResponseWriter +} + +// NewLogResponseWriter instanciates a new LogResponseWriter +func NewLogResponseWriter(res http.ResponseWriter) *LogResponseWriter { + // Default the status code to 200 + return &LogResponseWriter{200, 0, res} +} + +// Header returns & satisfies the http.ResponseWriter interface +func (w *LogResponseWriter) Header() http.Header { + return w.ResponseWriter.Header() +} + +// Write satisfies the http.ResponseWriter interface and +// captures data written, in bytes +func (w *LogResponseWriter) Write(data []byte) (int, error) { + + written, err := w.ResponseWriter.Write(data) + w.Size += written + + return written, err +} + +// WriteHeader satisfies the http.ResponseWriter interface and +// allows us to cach the status code +func (w *LogResponseWriter) WriteHeader(statusCode int) { + + w.Status = statusCode + w.ResponseWriter.WriteHeader(statusCode) +} diff --git a/main.go b/main.go index 820fc80..f0da838 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "crypto/md5" "fmt" "io/ioutil" + "log" "net/http" "time" @@ -49,10 +50,22 @@ func main() { go runWelcomePage(cfg) - http.Handle("/", r) + http.Handle("/", logHTTPRequest(r)) http.ListenAndServe(cfg.Listen, nil) } +func logHTTPRequest(h http.Handler) http.Handler { + return http.HandlerFunc(func(res http.ResponseWriter, r *http.Request) { + start := time.Now().UnixNano() + w := NewLogResponseWriter(res) + + h.ServeHTTP(w, r) + + d := (time.Now().UnixNano() - start) / 1000 + log.Printf("%s %s %d %dµs %dB\n", r.Method, r.URL.Path, w.Status, d, w.Size) + }) +} + func generateAPIKey() string { t := time.Now().String() sum := md5.Sum([]byte(t))