Skip to content

Commit

Permalink
Merge pull request #24 from elisasre/redisfixs
Browse files Browse the repository at this point in the history
check nil rdb client
  • Loading branch information
zetaab authored Nov 30, 2022
2 parents d3c3bda + 67a8584 commit 7895998
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func RedisRateLimiter(rdb *redis.Client, key KeyFunc, errFunc ErrFunc) gin.Handl
c.Abort()
return
}
if limit != nil {
if limit != nil && rdb != nil {
res, err := limiter.Allow(ctx, key, redis_rate.PerMinute(PtrValue(limit)))
if err == nil {
reset := time.Now().Add(res.ResetAfter)
Expand All @@ -53,6 +53,7 @@ func RedisRateLimiter(rdb *redis.Client, key KeyFunc, errFunc ErrFunc) gin.Handl
}
}
}

c.Next()
}
}
29 changes: 29 additions & 0 deletions ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,32 @@ func TestRedisRateLimiterForce(t *testing.T) {
require.Equal(t, "", w2.Result().Header.Get(ratelimitLimit))
require.Equal(t, "", w2.Result().Header.Get(ratelimitRemaining))
}

//nolint:bodyclose
func TestRedisRateLimiterNil(t *testing.T) {
nilLimiter := RedisRateLimiter(nil,
func(c *gin.Context) (key string, limit *int, err error) {
return "test-user", Int(2), nil
},
func(c *gin.Context, err error) bool {
if err != nil {
t.Log(err)
}
c.JSON(http.StatusBadRequest,
ErrorResponse{Code: http.StatusBadRequest, Message: err.Error()},
)
c.Abort()
return true
},
)
router := setupRouter(nilLimiter)

w := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/healthz", nil)
require.Equal(t, err, nil)
router.ServeHTTP(w, req)
require.Equal(t, 200, w.Code)
require.Equal(t, "ok", w.Body.String())
require.Equal(t, "", w.Result().Header.Get(ratelimitLimit))
require.Equal(t, "", w.Result().Header.Get(ratelimitRemaining))
}

0 comments on commit 7895998

Please sign in to comment.