-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlimiter.go
45 lines (34 loc) · 985 Bytes
/
limiter.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
package limiter
import (
"net/http"
"strconv"
"github.com/alexfalkowski/go-service/limiter"
"github.com/alexfalkowski/go-service/meta"
"github.com/alexfalkowski/go-service/transport/strings"
l "github.com/ulule/limiter/v3"
)
// Handler for limiter.
func NewHandler(limiter *l.Limiter, key limiter.KeyFunc) *Handler {
return &Handler{limiter: limiter, key: key}
}
// Handler for tracer.
type Handler struct {
limiter *l.Limiter
key limiter.KeyFunc
}
// ServeHTTP for limiter.
func (h *Handler) ServeHTTP(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
if h.limiter == nil || strings.IsHealth(req.URL.Path) {
next(res, req)
return
}
ctx := req.Context()
// Memory stores do not return error.
context, _ := h.limiter.Get(ctx, meta.ValueOrBlank(h.key(ctx)))
if context.Reached {
res.Header().Add("X-Rate-Limit-Limit", strconv.FormatInt(context.Limit, 10))
res.WriteHeader(http.StatusTooManyRequests)
return
}
next(res, req)
}