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) } }