Skip to content

Commit 743b6f2

Browse files
author
dcb9
committed
Remove global key prefix constant
1 parent d327cbf commit 743b6f2

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

rate.go

+8-8
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ import (
99
"github.com/go-redis/redis/v8"
1010
)
1111

12-
const redisPrefix = "rate:"
13-
1412
type rediser interface {
1513
Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd
1614
EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd
@@ -73,13 +71,15 @@ func PerHour(rate int) Limit {
7371

7472
// Limiter controls how frequently events are allowed to happen.
7573
type Limiter struct {
76-
rdb rediser
74+
rdb rediser
75+
keyPrefix string
7776
}
7877

7978
// NewLimiter returns a new Limiter.
80-
func NewLimiter(rdb rediser) *Limiter {
79+
func NewLimiter(rdb rediser, keyPrefix string) *Limiter {
8180
return &Limiter{
82-
rdb: rdb,
81+
rdb: rdb,
82+
keyPrefix: keyPrefix,
8383
}
8484
}
8585

@@ -96,7 +96,7 @@ func (l Limiter) AllowN(
9696
n int,
9797
) (*Result, error) {
9898
values := []interface{}{limit.Burst, limit.Rate, limit.Period.Seconds(), n}
99-
v, err := allowN.Run(ctx, l.rdb, []string{redisPrefix + key}, values...).Result()
99+
v, err := allowN.Run(ctx, l.rdb, []string{l.keyPrefix + key}, values...).Result()
100100
if err != nil {
101101
return nil, err
102102
}
@@ -132,7 +132,7 @@ func (l Limiter) AllowAtMost(
132132
n int,
133133
) (*Result, error) {
134134
values := []interface{}{limit.Burst, limit.Rate, limit.Period.Seconds(), n}
135-
v, err := allowAtMost.Run(ctx, l.rdb, []string{redisPrefix + key}, values...).Result()
135+
v, err := allowAtMost.Run(ctx, l.rdb, []string{l.keyPrefix + key}, values...).Result()
136136
if err != nil {
137137
return nil, err
138138
}
@@ -161,7 +161,7 @@ func (l Limiter) AllowAtMost(
161161

162162
// Reset gets a key and reset all limitations and previous usages
163163
func (l *Limiter) Reset(ctx context.Context, key string) error {
164-
return l.rdb.Del(ctx, redisPrefix+key).Err()
164+
return l.rdb.Del(ctx, l.keyPrefix+key).Err()
165165
}
166166

167167
func dur(f float64) time.Duration {

0 commit comments

Comments
 (0)