(t *testing.T)
| 262 | } |
| 263 | |
| 264 | func TestThrottleCustomStatusCode(t *testing.T) { |
| 265 | const timeout = time.Second * 3 |
| 266 | |
| 267 | wait := make(chan struct{}) |
| 268 | |
| 269 | r := chi.NewRouter() |
| 270 | r.Use(ThrottleWithOpts(ThrottleOpts{Limit: 1, StatusCode: http.StatusServiceUnavailable})) |
| 271 | r.Get("/", func(w http.ResponseWriter, r *http.Request) { |
| 272 | select { |
| 273 | case <-wait: |
| 274 | case <-time.After(timeout): |
| 275 | } |
| 276 | w.WriteHeader(http.StatusOK) |
| 277 | }) |
| 278 | server := httptest.NewServer(r) |
| 279 | defer server.Close() |
| 280 | |
| 281 | const totalRequestCount = 5 |
| 282 | |
| 283 | codes := make(chan int, totalRequestCount) |
| 284 | errs := make(chan error, totalRequestCount) |
| 285 | client := &http.Client{Timeout: timeout} |
| 286 | for range totalRequestCount { |
| 287 | go func() { |
| 288 | resp, err := client.Get(server.URL) |
| 289 | if err != nil { |
| 290 | errs <- err |
| 291 | return |
| 292 | } |
| 293 | codes <- resp.StatusCode |
| 294 | }() |
| 295 | } |
| 296 | |
| 297 | waitResponse := func(wantCode int) { |
| 298 | select { |
| 299 | case err := <-errs: |
| 300 | t.Fatal(err) |
| 301 | case code := <-codes: |
| 302 | assertEqual(t, wantCode, code) |
| 303 | case <-time.After(timeout): |
| 304 | t.Fatalf("waiting %d code, timeout exceeded", wantCode) |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | for range totalRequestCount - 1 { |
| 309 | waitResponse(http.StatusServiceUnavailable) |
| 310 | } |
| 311 | close(wait) // Allow the last request to proceed. |
| 312 | waitResponse(http.StatusOK) |
| 313 | } |
| 314 | |
| 315 | func BenchmarkThrottle(b *testing.B) { |
| 316 | throttleMiddleware := ThrottleBacklog(1000, 50, time.Second) |
nothing calls this directly
no test coverage detected