-
Notifications
You must be signed in to change notification settings - Fork 0
/
opts.go
71 lines (63 loc) · 1.29 KB
/
opts.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
package ratelimiter
import (
"hash"
"net/http"
"time"
"github.com/urfave/negroni"
)
type GetKeyFunc func(*http.Request) string
type GetQuotaFunc func(string) Quota
type GetHasherFunc func() hash.Hash32
type opts struct {
status int
buckets int
getKey GetKeyFunc
getHasher GetHasherFunc
getQuota GetQuotaFunc
}
func getDefaults() opts {
return opts{
status: http.StatusTooManyRequests,
buckets: 0,
getKey: nil,
getHasher: nil,
getQuota: func(key string) Quota {
return InfQuota
},
}
}
func NewGlobal() opts {
op := getDefaults()
return op
}
func NewLimitByKeys(getKey GetKeyFunc) opts {
op := getDefaults()
op.getKey = getKey
op.getHasher = nil
op.buckets = 0
return op
}
func NewLimitByBucketedKeys(buckets int, getHasher GetHasherFunc, getKey GetKeyFunc) opts {
op := getDefaults()
op.getKey = getKey
op.getHasher = getHasher
op.buckets = buckets
return op
}
func (o opts) WithQuotaByKeys(getQuota GetQuotaFunc) opts {
o.getQuota = getQuota
return o
}
func (o opts) WithStatus(status int) opts {
o.status = status
return o
}
func (o opts) WithDefaultQuota(reqs int, interval time.Duration) opts {
o.getQuota = func(key string) Quota {
return NewQuota(reqs, interval)
}
return o
}
func (o opts) Middleware() negroni.Handler {
return newRL(o)
}