From 34436d11e24884e190b5addb8fb575ad2676eb3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Tikvi=C4=87?= Date: Fri, 15 Jun 2018 11:16:39 +0200 Subject: [PATCH] in-out http logs are written at the same time --- http.go | 22 ++++++++++++++++++++-- middleware.go | 14 +++++++++----- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/http.go b/http.go index 54670db..11a3ae1 100644 --- a/http.go +++ b/http.go @@ -6,6 +6,24 @@ import ( "net/http" ) +type ResponseWriterStatusRecorder struct { + http.ResponseWriter + status int +} + +func WrapWithStatusRecorder(w http.ResponseWriter) *ResponseWriterStatusRecorder { + return &ResponseWriterStatusRecorder{w, 0} +} + +func (r *ResponseWriterStatusRecorder) WriteHeader(code int) { + r.status = code + r.ResponseWriter.WriteHeader(code) +} + +func (r *ResponseWriterStatusRecorder) Status() int { + return r.status +} + // NotFoundHandlerFunc writes HTTP error 404 to w. func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) { SetDefaultHeaders(w) @@ -19,11 +37,11 @@ func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) { func SetDefaultHeaders(w http.ResponseWriter) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", `Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization`) + w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") w.Header().Set("Content-Type", "application/json; charset=utf-8") } -func ReqLocale(req *http.Request, dflt string) string { +func GetLocale(req *http.Request, dflt string) string { loc := req.FormValue("locale") if loc == "" { return dflt diff --git a/middleware.go b/middleware.go index cd58b26..1ba932f 100644 --- a/middleware.go +++ b/middleware.go @@ -28,21 +28,25 @@ func ParseForm(h http.HandlerFunc) http.HandlerFunc { } } -var reqLogger *gologger.Logger +var trafficLogger *gologger.Logger func EnableLogging(log string) error { var err error - reqLogger, err = gologger.New(log, gologger.MaxLogSize5MB) + trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB) return err } func Log(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { - reqLogger.LogRequest(req, "") + in := trafficLogger.RequestLog(req, "") + + w2 := WrapWithStatusRecorder(w) t1 := time.Now() - h(w, req) + h(w2, req) t2 := time.Now() - reqLogger.LogResponse(w, req, t2.Sub(t1)) + + out := trafficLogger.ResponseLog(w2.Status(), t2.Sub(t1)) + trafficLogger.LogHTTPTraffic(in, out) } } -- 1.8.1.2