package analytics import ( "context" "net/http" sharedhttp "alin.ovh/homestead/shared/http" ) type contextKey struct{} var countKeyContextKey contextKey func WithCountKey(r *http.Request, key string) *http.Request { return r.WithContext(context.WithValue(r.Context(), countKeyContextKey, key)) } func GetCountKey(r *http.Request) (string, bool) { key, ok := r.Context().Value(countKeyContextKey).(string) return key, ok } 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 := sharedhttp.NewStatusCapturingResponseWriter(w) next.ServeHTTP(rw, r) countKey, ok := GetCountKey(r) if !ok { if rw.Status >= 201 { countKey = http.StatusText(rw.Status) } else { countKey = r.URL.Path } } counter.Count(r, countKey) }) } }