(t *testing.T)
| 72 | } |
| 73 | |
| 74 | func TestRateLimiterWithConfig(t *testing.T) { |
| 75 | var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) |
| 76 | |
| 77 | e := echo.New() |
| 78 | |
| 79 | handler := func(c *echo.Context) error { |
| 80 | return c.String(http.StatusOK, "test") |
| 81 | } |
| 82 | |
| 83 | mw, err := RateLimiterConfig{ |
| 84 | IdentifierExtractor: func(c *echo.Context) (string, error) { |
| 85 | id := c.Request().Header.Get(echo.HeaderXRealIP) |
| 86 | if id == "" { |
| 87 | return "", errors.New("invalid identifier") |
| 88 | } |
| 89 | return id, nil |
| 90 | }, |
| 91 | DenyHandler: func(ctx *echo.Context, identifier string, err error) error { |
| 92 | return ctx.JSON(http.StatusForbidden, nil) |
| 93 | }, |
| 94 | ErrorHandler: func(ctx *echo.Context, err error) error { |
| 95 | return ctx.JSON(http.StatusBadRequest, nil) |
| 96 | }, |
| 97 | Store: inMemoryStore, |
| 98 | }.ToMiddleware() |
| 99 | assert.NoError(t, err) |
| 100 | |
| 101 | testCases := []struct { |
| 102 | id string |
| 103 | code int |
| 104 | }{ |
| 105 | {"127.0.0.1", http.StatusOK}, |
| 106 | {"127.0.0.1", http.StatusOK}, |
| 107 | {"127.0.0.1", http.StatusOK}, |
| 108 | {"127.0.0.1", http.StatusForbidden}, |
| 109 | {"", http.StatusBadRequest}, |
| 110 | {"127.0.0.1", http.StatusForbidden}, |
| 111 | {"127.0.0.1", http.StatusForbidden}, |
| 112 | } |
| 113 | |
| 114 | for _, tc := range testCases { |
| 115 | req := httptest.NewRequest(http.MethodGet, "/", nil) |
| 116 | req.Header.Add(echo.HeaderXRealIP, tc.id) |
| 117 | |
| 118 | rec := httptest.NewRecorder() |
| 119 | |
| 120 | c := e.NewContext(req, rec) |
| 121 | |
| 122 | err := mw(handler)(c) |
| 123 | |
| 124 | assert.NoError(t, err) |
| 125 | assert.Equal(t, tc.code, rec.Code) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func TestRateLimiterWithConfig_defaultDenyHandler(t *testing.T) { |
| 130 | var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) |
nothing calls this directly
no test coverage detected
searching dependent graphs…