()
| 684 | } |
| 685 | |
| 686 | func (ts *MiddlewareTestSuite) TestLimitHandler() { |
| 687 | ts.Config.RateLimitHeader = "X-Rate-Limit" |
| 688 | lmt := tollbooth.NewLimiter(5, &limiter.ExpirableOptions{ |
| 689 | DefaultExpirationTTL: time.Hour, |
| 690 | }) |
| 691 | |
| 692 | okHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 693 | w.WriteHeader(http.StatusOK) |
| 694 | b, _ := json.Marshal(map[string]interface{}{"message": "ok"}) |
| 695 | w.Write([]byte(b)) |
| 696 | }) |
| 697 | |
| 698 | for i := 0; i < 5; i++ { |
| 699 | req := httptest.NewRequest(http.MethodGet, "http://localhost", nil) |
| 700 | req.Header.Add(ts.Config.RateLimitHeader, "0.0.0.0") |
| 701 | w := httptest.NewRecorder() |
| 702 | ts.API.limitHandler(lmt).handler(okHandler).ServeHTTP(w, req) |
| 703 | require.Equal(ts.T(), http.StatusOK, w.Code) |
| 704 | |
| 705 | var data map[string]interface{} |
| 706 | require.NoError(ts.T(), json.NewDecoder(w.Body).Decode(&data)) |
| 707 | require.Equal(ts.T(), "ok", data["message"]) |
| 708 | } |
| 709 | |
| 710 | // 6th request should fail and return a rate limit exceeded error |
| 711 | req := httptest.NewRequest(http.MethodGet, "http://localhost", nil) |
| 712 | req.Header.Add(ts.Config.RateLimitHeader, "0.0.0.0") |
| 713 | w := httptest.NewRecorder() |
| 714 | ts.API.limitHandler(lmt).handler(okHandler).ServeHTTP(w, req) |
| 715 | require.Equal(ts.T(), http.StatusTooManyRequests, w.Code) |
| 716 | } |
| 717 | |
| 718 | func (ts *MiddlewareTestSuite) TestLimitRequestBodyMiddleware() { |
| 719 | const maxBytes = 1 << 10 // 1KB for testing |
nothing calls this directly
no test coverage detected