-
Notifications
You must be signed in to change notification settings - Fork 2
/
limiter.go
38 lines (30 loc) · 865 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
package main
import (
"net/http"
"sync"
"github.com/Sambruk/windermere/scimserverlite"
"golang.org/x/time/rate"
)
// Limiter returns a middleware with token bucket rate limiting applied per tenant
func Limiter(h http.Handler, tenantGetter scimserverlite.TenantGetter, r rate.Limit, b int) http.Handler {
limiters := make(map[string]*rate.Limiter)
var lock sync.Mutex
getLimiter := func(entity string) *rate.Limiter {
lock.Lock()
defer lock.Unlock()
if limiter, ok := limiters[entity]; ok {
return limiter
}
limiter := rate.NewLimiter(r, b)
limiters[entity] = limiter
return limiter
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
limiter := getLimiter(tenantGetter(r.Context()))
if limiter.Wait(r.Context()) != nil {
w.WriteHeader(http.StatusTooManyRequests)
return
}
h.ServeHTTP(w, r)
})
}