99 "github.com/go-redis/redis/v8"
1010)
1111
12- const redisPrefix = "rate:"
13-
1412type 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.
7573type 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
163163func (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
167167func dur (f float64 ) time.Duration {
0 commit comments