39 lines
938 B
Go
39 lines
938 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func TestRateLimitByClientIPBlocksAfterLimit(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
router := gin.New()
|
|
router.GET(
|
|
"/limited",
|
|
RateLimitByClientIP(2, time.Minute, 42961, "rate_limited", "too many requests"),
|
|
func(c *gin.Context) {
|
|
c.Status(http.StatusNoContent)
|
|
},
|
|
)
|
|
|
|
for i := 0; i < 2; i++ {
|
|
req := httptest.NewRequest(http.MethodGet, "/limited", nil)
|
|
res := httptest.NewRecorder()
|
|
router.ServeHTTP(res, req)
|
|
if res.Code != http.StatusNoContent {
|
|
t.Fatalf("request %d status = %d, want %d", i+1, res.Code, http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/limited", nil)
|
|
res := httptest.NewRecorder()
|
|
router.ServeHTTP(res, req)
|
|
if res.Code != http.StatusTooManyRequests {
|
|
t.Fatalf("third request status = %d, want %d", res.Code, http.StatusTooManyRequests)
|
|
}
|
|
}
|