all repos — homestead @ 8267148e988f22647aa735652dafd06c692b047f

Code for my website

domain/analytics/middleware.go (view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package analytics

import (
	"context"
	"net/http"

	sharedhttp "alin.ovh/homestead/shared/http"
)

type contextKey struct{}

var titleContextKey contextKey

func WithTitle(r *http.Request, key string) *http.Request {
	return r.WithContext(context.WithValue(r.Context(), titleContextKey, key))
}

func GetTitle(r *http.Request) (string, bool) {
	key, ok := r.Context().Value(titleContextKey).(string)

	return key, ok
}

func CounterMiddleware(counter Counter, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rw := sharedhttp.NewStatusCapturingResponseWriter(w)

		next.ServeHTTP(rw, r)

		title, ok := GetTitle(r)
		if !ok {
			if rw.Status >= 201 {
				title = http.StatusText(rw.Status)
			}
		}

		if rw.Status <= 299 {
			counter.Count(r, title)
		}
	})
}