Skip to content

Commit

Permalink
update rate limitter to use APIError
Browse files Browse the repository at this point in the history
  • Loading branch information
juancwu committed Dec 24, 2024
1 parent 3057152 commit fb9be8b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
9 changes: 7 additions & 2 deletions backend/internal/middleware/rate_limit.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package middleware

import (
"KonferCA/SPUR/internal/v1/v1_common"
"net/http"
"sync"
"time"
Expand Down Expand Up @@ -122,9 +123,11 @@ func (rl *RateLimiter) RateLimit() echo.MiddlewareFunc {
Dur("remaining", remaining).
Msg("request blocked: rate limit exceeded")

return echo.NewHTTPError(
return v1_common.Fail(
c,
http.StatusTooManyRequests,
"too many requests, please try again in "+remaining.Round(time.Second).String(),
nil,
)
}

Expand All @@ -151,9 +154,11 @@ func (rl *RateLimiter) RateLimit() echo.MiddlewareFunc {
Dur("block_duration", blockDuration).
Msg("IP blocked: rate limit exceeded")

return echo.NewHTTPError(
return v1_common.Fail(
c,
http.StatusTooManyRequests,
"too many requests, please try again in "+blockDuration.Round(time.Second).String(),
nil,
)
}

Expand Down
9 changes: 5 additions & 4 deletions backend/internal/tests/rate_limit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"time"

"KonferCA/SPUR/internal/middleware"
"KonferCA/SPUR/internal/v1/v1_common"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -69,7 +70,7 @@ func TestRateLimiter(t *testing.T) {
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
err = h(c)
he, ok := err.(*echo.HTTPError)
he, ok := err.(*v1_common.APIError)
assert.True(t, ok)
assert.Equal(t, http.StatusTooManyRequests, he.Code)
})
Expand Down Expand Up @@ -103,7 +104,7 @@ func TestRateLimiter(t *testing.T) {
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
err = h(c)
he, ok := err.(*echo.HTTPError)
he, ok := err.(*v1_common.APIError)
assert.True(t, ok)
assert.Equal(t, http.StatusTooManyRequests, he.Code)
}
Expand Down Expand Up @@ -137,7 +138,7 @@ func TestRateLimiter(t *testing.T) {
c = e.NewContext(req, rec)
err = h(c)
assert.Error(t, err)
he, ok := err.(*echo.HTTPError)
he, ok := err.(*v1_common.APIError)
assert.True(t, ok)
assert.Equal(t, http.StatusTooManyRequests, he.Code)

Expand Down Expand Up @@ -179,7 +180,7 @@ func TestRateLimiter(t *testing.T) {
c = e.NewContext(req, rec)
err = h(c)
assert.Error(t, err)
he, ok := err.(*echo.HTTPError)
he, ok := err.(*v1_common.APIError)
assert.True(t, ok)
assert.Equal(t, http.StatusTooManyRequests, he.Code)

Expand Down

0 comments on commit fb9be8b

Please sign in to comment.