29 lines
775 B
Go
29 lines
775 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func TestRateLimitByIPReturns429AfterWindowIsConsumed(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.GET("/rate-test", RateLimitByIP(1, time.Minute), func(c *gin.Context) {
|
|
c.Status(http.StatusNoContent)
|
|
})
|
|
first := httptest.NewRecorder()
|
|
r.ServeHTTP(first, httptest.NewRequest(http.MethodGet, "/rate-test", nil))
|
|
if first.Code != http.StatusNoContent {
|
|
t.Fatalf("首个请求状态码 = %d", first.Code)
|
|
}
|
|
second := httptest.NewRecorder()
|
|
r.ServeHTTP(second, httptest.NewRequest(http.MethodGet, "/rate-test", nil))
|
|
if second.Code != http.StatusTooManyRequests {
|
|
t.Fatalf("超限请求状态码 = %d,期望 429", second.Code)
|
|
}
|
|
}
|