Commit f38e87cf4cc29108b558d5a97a1fef09e203c337

Authored by Marko Tikvić
1 parent 8a070abe23
Exists in master

status recorder

Showing 2 changed files with 35 additions and 15 deletions   Show diff stats
... ... @@ -6,24 +6,45 @@ import (
6 6 "net/http"
7 7 )
8 8  
9   -type ResponseWriterStatusRecorder struct {
10   - http.ResponseWriter
  9 +type StatusRecorder struct {
  10 + writer http.ResponseWriter
11 11 status int
  12 + size int
12 13 }
13 14  
14   -func WrapWithStatusRecorder(w http.ResponseWriter) *ResponseWriterStatusRecorder {
15   - return &ResponseWriterStatusRecorder{w, 0}
  15 +func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder {
  16 + return &StatusRecorder{
  17 + writer: w,
  18 + status: 0,
  19 + size: 0,
  20 + }
16 21 }
17 22  
18   -func (r *ResponseWriterStatusRecorder) WriteHeader(code int) {
  23 +// http.ResponseWriter interface
  24 +func (r *StatusRecorder) WriteHeader(code int) {
19 25 r.status = code
20   - r.ResponseWriter.WriteHeader(code)
  26 + r.writer.WriteHeader(code)
  27 +}
  28 +
  29 +// http.ResponseWriter interface
  30 +func (r *StatusRecorder) Write(in []byte) (int, error) {
  31 + r.size = len(in)
  32 + return r.writer.Write(in)
21 33 }
22 34  
23   -func (r *ResponseWriterStatusRecorder) Status() int {
  35 +// http.ResponseWriter interface
  36 +func (r *StatusRecorder) Header() http.Header {
  37 + return r.writer.Header()
  38 +}
  39 +
  40 +func (r *StatusRecorder) Status() int {
24 41 return r.status
25 42 }
26 43  
  44 +func (r *StatusRecorder) Size() int {
  45 + return r.size
  46 +}
  47 +
27 48 // NotFoundHandlerFunc writes HTTP error 404 to w.
28 49 func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) {
29 50 SetDefaultHeaders(w)
... ...
middleware_log.go
... ... @@ -7,10 +7,10 @@ import (
7 7 "git.to-net.rs/marko.tikvic/gologger"
8 8 )
9 9  
10   -var trafficLogger *gologger.Logger
  10 +var httpLogger *gologger.Logger
11 11  
12 12 func EnableLogging(log string) (err error) {
13   - trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
  13 + httpLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
14 14 return err
15 15 }
16 16  
... ... @@ -19,16 +19,15 @@ func Log(h http.HandlerFunc) http.HandlerFunc {
19 19 t1 := time.Now()
20 20  
21 21 claims, _ := GetTokenClaims(req)
  22 + in := httpLogger.LogHTTPRequest(req, claims.Username)
22 23  
23   - in := trafficLogger.RequestLog(req, claims.Username)
  24 + rec := NewStatusRecorder(w)
24 25  
25   - wRec := WrapWithStatusRecorder(w)
26   - h(wRec, req)
  26 + h(rec, req)
27 27  
28 28 t2 := time.Now()
  29 + out := httpLogger.LogHTTPResponse(rec.Status(), t2.Sub(t1), rec.Size())
29 30  
30   - out := trafficLogger.ResponseLog(wRec.Status(), t2.Sub(t1), 0)
31   -
32   - trafficLogger.LogHTTPTraffic(in, out)
  31 + httpLogger.CombineHTTPLogs(in, out)
33 32 }
34 33 }
... ...