all repos — homestead @ 83369daabc06fafd62316d611baed63fb2900d95

Code for my website

extract and de-duplicate HTTP status capture

Alan Pearce
commit

83369daabc06fafd62316d611baed63fb2900d95

parent

8e31c2454617b413cc672c7561bb512555496927

3 files changed, 28 insertions(+), 36 deletions(-)

changed files
M domain/analytics/middleware.godomain/analytics/middleware.go
@@ -3,6 +3,8 @@
import ( "context" "net/http" + + sharedhttp "alin.ovh/homestead/shared/http" ) type contextKey struct{}
@@ -22,14 +24,14 @@
func CounterMiddleware(counter Counter) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - rw := newStatusCapturingResponseWriter(w) + rw := sharedhttp.NewStatusCapturingResponseWriter(w) next.ServeHTTP(rw, r) countKey, ok := GetCountKey(r) if !ok { - if rw.status >= 201 { - countKey = http.StatusText(rw.status) + if rw.Status >= 201 { + countKey = http.StatusText(rw.Status) } else { countKey = r.URL.Path }
@@ -39,17 +41,3 @@ counter.Count(r, countKey)
}) } } - -type statusCapturingResponseWriter struct { - http.ResponseWriter - status int -} - -func newStatusCapturingResponseWriter(w http.ResponseWriter) *statusCapturingResponseWriter { - return &statusCapturingResponseWriter{w, http.StatusOK} -} - -func (w *statusCapturingResponseWriter) WriteHeader(code int) { - w.status = code - w.ResponseWriter.WriteHeader(code) -}
M domain/web/server/logging.godomain/web/server/logging.go
@@ -3,34 +3,19 @@
import ( "net/http" + sharedhttp "alin.ovh/homestead/shared/http" + "alin.ovh/x/log" ) -type LoggingResponseWriter struct { - http.ResponseWriter - statusCode int -} - -func (lrw *LoggingResponseWriter) WriteHeader(code int) { - lrw.statusCode = code - // avoids warning: superfluous response.WriteHeader call - if lrw.statusCode != http.StatusOK { - lrw.ResponseWriter.WriteHeader(code) - } -} - -func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter { - return &LoggingResponseWriter{w, http.StatusOK} -} - func wrapHandlerWithLogging(wrappedHandler http.Handler, log *log.Logger) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - lw := NewLoggingResponseWriter(w) + lw := sharedhttp.NewStatusCapturingResponseWriter(w) wrappedHandler.ServeHTTP(lw, r) log.Info( "http request", "method", r.Method, - "status", lw.statusCode, + "status", lw.Status, "host", r.Host, "path", r.URL.Path, "location", lw.Header().Get("Location"),
A shared/http/responsewriter.go
@@ -0,0 +1,19 @@
+package http + +import ( + "net/http" +) + +type StatusCapturingResponseWriter struct { + http.ResponseWriter + Status int +} + +func NewStatusCapturingResponseWriter(w http.ResponseWriter) *StatusCapturingResponseWriter { + return &StatusCapturingResponseWriter{w, http.StatusOK} +} + +func (w *StatusCapturingResponseWriter) WriteHeader(code int) { + w.Status = code + w.ResponseWriter.WriteHeader(code) +}