@@ -73,14 +73,34 @@ func PerHour(rate int) Limit {
73
73
74
74
// Limiter controls how frequently events are allowed to happen.
75
75
type Limiter struct {
76
- rdb rediser
76
+ rdb rediser
77
+ keyPrefix string
77
78
}
78
79
80
+ type Option func (* Limiter )
81
+
79
82
// NewLimiter returns a new Limiter.
80
- func NewLimiter (rdb rediser ) * Limiter {
81
- return & Limiter {
83
+ func NewLimiter (rdb rediser , options ... Option ) * Limiter {
84
+ limiter := & Limiter {
82
85
rdb : rdb ,
83
86
}
87
+
88
+ for _ , opt := range options {
89
+ opt (limiter )
90
+ }
91
+
92
+ if limiter .keyPrefix == "" {
93
+ limiter .keyPrefix = redisPrefix
94
+ }
95
+
96
+ return limiter
97
+ }
98
+
99
+ // WithKeyPrefix is a functional option to set the redis key prefix.
100
+ func WithKeyPrefix (keyPrefix string ) Option {
101
+ return func (l * Limiter ) {
102
+ l .keyPrefix = keyPrefix
103
+ }
84
104
}
85
105
86
106
// Allow is a shortcut for AllowN(ctx, key, limit, 1).
@@ -96,7 +116,7 @@ func (l Limiter) AllowN(
96
116
n int ,
97
117
) (* Result , error ) {
98
118
values := []interface {}{limit .Burst , limit .Rate , limit .Period .Seconds (), n }
99
- v , err := allowN .Run (ctx , l .rdb , []string {redisPrefix + key }, values ... ).Result ()
119
+ v , err := allowN .Run (ctx , l .rdb , []string {l . keyPrefix + key }, values ... ).Result ()
100
120
if err != nil {
101
121
return nil , err
102
122
}
@@ -132,7 +152,7 @@ func (l Limiter) AllowAtMost(
132
152
n int ,
133
153
) (* Result , error ) {
134
154
values := []interface {}{limit .Burst , limit .Rate , limit .Period .Seconds (), n }
135
- v , err := allowAtMost .Run (ctx , l .rdb , []string {redisPrefix + key }, values ... ).Result ()
155
+ v , err := allowAtMost .Run (ctx , l .rdb , []string {l . keyPrefix + key }, values ... ).Result ()
136
156
if err != nil {
137
157
return nil , err
138
158
}
@@ -161,7 +181,7 @@ func (l Limiter) AllowAtMost(
161
181
162
182
// Reset gets a key and reset all limitations and previous usages
163
183
func (l * Limiter ) Reset (ctx context.Context , key string ) error {
164
- return l .rdb .Del (ctx , redisPrefix + key ).Err ()
184
+ return l .rdb .Del (ctx , l . keyPrefix + key ).Err ()
165
185
}
166
186
167
187
func dur (f float64 ) time.Duration {
0 commit comments