-
Notifications
You must be signed in to change notification settings - Fork 16
/
middleware.go
168 lines (138 loc) · 3.88 KB
/
middleware.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package api
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog/log"
"github.com/sksmith/go-micro-example/core"
"github.com/sksmith/go-micro-example/core/user"
)
const DefaultPageLimit = 50
type CtxKey string
const (
CtxKeyLimit CtxKey = "limit"
CtxKeyOffset CtxKey = "offset"
CtxKeyUser CtxKey = "user"
)
func Paginate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
limitStr := r.URL.Query().Get("limit")
offsetStr := r.URL.Query().Get("offset")
var err error
limit := DefaultPageLimit
if limitStr != "" {
limit, err = strconv.Atoi(limitStr)
if err != nil {
limit = DefaultPageLimit
}
}
offset := 0
if offsetStr != "" {
offset, err = strconv.Atoi(offsetStr)
if err != nil {
offset = 0
}
}
ctx := context.WithValue(r.Context(), CtxKeyLimit, limit)
ctx = context.WithValue(ctx, CtxKeyOffset, offset)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
type UserAccess interface {
Login(ctx context.Context, username, password string) (user.User, error)
}
func Authenticate(ua UserAccess) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok {
authErr(w)
return
}
u, err := ua.Login(r.Context(), username, password)
if err != nil {
if errors.Is(err, core.ErrNotFound) {
authErr(w)
} else {
log.Error().Err(err).Str("username", username).Msg("error acquiring user")
Render(w, r, ErrInternalServer)
}
return
}
ctx := context.WithValue(r.Context(), CtxKeyUser, u)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func AdminOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
usr, ok := r.Context().Value(CtxKeyUser).(user.User)
if !ok || !usr.IsAdmin {
authErr(w)
return
}
next.ServeHTTP(w, r)
})
}
func authErr(w http.ResponseWriter) {
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
func Logging(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
defer func() {
dur := fmt.Sprintf("%dms", time.Duration(time.Since(start).Milliseconds()))
log.Trace().
Str("method", r.Method).
Str("host", r.Host).
Str("uri", r.RequestURI).
Str("proto", r.Proto).
Str("origin", r.Header.Get("Origin")).
Int("status", ww.Status()).
Int("bytes", ww.BytesWritten()).
Str("duration", dur).Send()
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
func Metrics(next http.Handler) http.Handler {
urlHitCount := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "url_hit_count",
Help: "Number of times the given url was hit",
},
[]string{"method", "url"},
)
urlLatency := prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "url_latency",
Help: "The latency quantiles for the given URL",
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
},
[]string{"method", "url"},
)
prometheus.MustRegister(urlHitCount)
prometheus.MustRegister(urlLatency)
fn := func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
ctx := chi.RouteContext(r.Context())
if len(ctx.RoutePatterns) > 0 {
dur := float64(time.Since(start).Milliseconds())
urlLatency.WithLabelValues(ctx.RouteMethod, ctx.RoutePatterns[0]).Observe(dur)
urlHitCount.WithLabelValues(ctx.RouteMethod, ctx.RoutePatterns[0]).Inc()
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}