-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathratelimiter.go
More file actions
43 lines (33 loc) · 806 Bytes
/
ratelimiter.go
File metadata and controls
43 lines (33 loc) · 806 Bytes
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
package main
import (
"net/http"
"sync"
"github.com/didip/tollbooth/libstring"
"github.com/juju/ratelimit"
)
type BucketFactory func() *ratelimit.Bucket
type RateLimiter struct {
bucketFactory BucketFactory
buckets map[string]*ratelimit.Bucket
mutex sync.Mutex
}
func NewRateLimiter(f BucketFactory) *RateLimiter {
return &RateLimiter{
bucketFactory: f,
buckets: make(map[string]*ratelimit.Bucket),
}
}
func (r *RateLimiter) Get(key string) *ratelimit.Bucket {
r.mutex.Lock()
defer r.mutex.Unlock()
b, ok := r.buckets[key]
if !ok {
b = r.bucketFactory()
r.buckets[key] = b
}
return b
}
var ipLookupFields = []string{"X-Forwarded-For", "X-Real-IP", "RemoteAddr"}
func RemoteIP(r *http.Request) string {
return libstring.RemoteIP(ipLookupFields, 0, r)
}