From f38e87cf4cc29108b558d5a97a1fef09e203c337 Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Wed, 6 Feb 2019 10:47:18 +0100 Subject: [PATCH] status recorder --- http.go | 35 ++++++++++++++++++++++++++++------- middleware_log.go | 15 +++++++-------- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/http.go b/http.go index 11a3ae1..932de59 100644 --- a/http.go +++ b/http.go @@ -6,24 +6,45 @@ import ( "net/http" ) -type ResponseWriterStatusRecorder struct { - http.ResponseWriter +type StatusRecorder struct { + writer http.ResponseWriter status int + size int } -func WrapWithStatusRecorder(w http.ResponseWriter) *ResponseWriterStatusRecorder { - return &ResponseWriterStatusRecorder{w, 0} +func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder { + return &StatusRecorder{ + writer: w, + status: 0, + size: 0, + } } -func (r *ResponseWriterStatusRecorder) WriteHeader(code int) { +// http.ResponseWriter interface +func (r *StatusRecorder) WriteHeader(code int) { r.status = code - r.ResponseWriter.WriteHeader(code) + r.writer.WriteHeader(code) +} + +// http.ResponseWriter interface +func (r *StatusRecorder) Write(in []byte) (int, error) { + r.size = len(in) + return r.writer.Write(in) } -func (r *ResponseWriterStatusRecorder) Status() int { +// http.ResponseWriter interface +func (r *StatusRecorder) Header() http.Header { + return r.writer.Header() +} + +func (r *StatusRecorder) Status() int { return r.status } +func (r *StatusRecorder) Size() int { + return r.size +} + // NotFoundHandlerFunc writes HTTP error 404 to w. func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) { SetDefaultHeaders(w) diff --git a/middleware_log.go b/middleware_log.go index c1ffe16..cabc647 100644 --- a/middleware_log.go +++ b/middleware_log.go @@ -7,10 +7,10 @@ import ( "git.to-net.rs/marko.tikvic/gologger" ) -var trafficLogger *gologger.Logger +var httpLogger *gologger.Logger func EnableLogging(log string) (err error) { - trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB) + httpLogger, err = gologger.New(log, gologger.MaxLogSize5MB) return err } @@ -19,16 +19,15 @@ func Log(h http.HandlerFunc) http.HandlerFunc { t1 := time.Now() claims, _ := GetTokenClaims(req) + in := httpLogger.LogHTTPRequest(req, claims.Username) - in := trafficLogger.RequestLog(req, claims.Username) + rec := NewStatusRecorder(w) - wRec := WrapWithStatusRecorder(w) - h(wRec, req) + h(rec, req) t2 := time.Now() + out := httpLogger.LogHTTPResponse(rec.Status(), t2.Sub(t1), rec.Size()) - out := trafficLogger.ResponseLog(wRec.Status(), t2.Sub(t1), 0) - - trafficLogger.LogHTTPTraffic(in, out) + httpLogger.CombineHTTPLogs(in, out) } } -- 1.8.1.2