Skip to content

Commit 326ae61

Browse files
authored
Merge pull request #43 from sashati/v9
Add Reset function to remove history of a key
2 parents 19dc8f9 + ff6739e commit 326ae61

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

rate.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type rediser interface {
1616
EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd
1717
ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd
1818
ScriptLoad(ctx context.Context, script string) *redis.StringCmd
19+
Del(ctx context.Context, keys ...string) *redis.IntCmd
1920
}
2021

2122
type Limit struct {
@@ -158,6 +159,11 @@ func (l Limiter) AllowAtMost(
158159
return res, nil
159160
}
160161

162+
// Reset gets a key and reset all limitations and previous usages
163+
func (l *Limiter) Reset(ctx context.Context, key string) error {
164+
return l.rdb.Del(ctx, redisPrefix+key).Err()
165+
}
166+
161167
func dur(f float64) time.Duration {
162168
if f == -1 {
163169
return -1

rate_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ func TestAllow(t *testing.T) {
3737
assert.Equal(t, res.RetryAfter, time.Duration(-1))
3838
assert.InDelta(t, res.ResetAfter, 100*time.Millisecond, float64(10*time.Millisecond))
3939

40+
err = l.Reset(ctx, "test_id")
41+
assert.Nil(t, err)
42+
res, err = l.Allow(ctx, "test_id", limit)
43+
assert.Nil(t, err)
44+
assert.Equal(t, res.Allowed, 1)
45+
assert.Equal(t, res.Remaining, 9)
46+
assert.Equal(t, res.RetryAfter, time.Duration(-1))
47+
assert.InDelta(t, res.ResetAfter, 100*time.Millisecond, float64(10*time.Millisecond))
48+
4049
res, err = l.AllowN(ctx, "test_id", limit, 2)
4150
assert.Nil(t, err)
4251
assert.Equal(t, res.Allowed, 2)
@@ -57,6 +66,7 @@ func TestAllow(t *testing.T) {
5766
assert.Equal(t, res.Remaining, 0)
5867
assert.InDelta(t, res.RetryAfter, 99*time.Second, float64(time.Second))
5968
assert.InDelta(t, res.ResetAfter, 999*time.Millisecond, float64(10*time.Millisecond))
69+
6070
}
6171

6272
func TestRetryAfter(t *testing.T) {

0 commit comments

Comments
 (0)