11 type testHandler struct {
12 inHandler chan struct{}
13 okToProceed chan struct{}
16 func (h *testHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
17 h.inHandler <- struct{}{}
21 func newTestHandler(maxReqs int) *testHandler {
23 inHandler: make(chan struct{}),
24 okToProceed: make(chan struct{}),
28 func TestRequestLimiter1(t *testing.T) {
29 h := newTestHandler(10)
30 l := NewRequestLimiter(1, h)
32 resps := make([]*httptest.ResponseRecorder, 10)
33 for i := 0; i < 10; i++ {
35 resps[i] = httptest.NewRecorder()
37 l.ServeHTTP(resps[i], &http.Request{})
41 done := make(chan struct{})
43 // Make sure one request has entered the handler
45 // Make sure all unsuccessful requests finish (but don't wait
46 // for the one that's still waiting for okToProceed)
49 // Wait for the last goroutine
51 h.okToProceed <- struct{}{}
57 case <-time.After(10 * time.Second):
58 t.Fatal("test timed out, probably deadlocked")
62 for i := 0; i < 10; i++ {
63 switch resps[i].Code {
69 t.Fatalf("Unexpected response code %d", resps[i].Code)
72 if n200 != 1 || n503 != 9 {
73 t.Fatalf("Got %d 200 responses, %d 503 responses (expected 1, 9)", n200, n503)
75 // Now that all 10 are finished, an 11th request should
79 h.okToProceed <- struct{}{}
81 resp := httptest.NewRecorder()
82 l.ServeHTTP(resp, &http.Request{})
84 t.Errorf("Got status %d on 11th request, want 200", resp.Code)
88 func TestRequestLimiter10(t *testing.T) {
89 h := newTestHandler(10)
90 l := NewRequestLimiter(10, h)
92 for i := 0; i < 10; i++ {
95 l.ServeHTTP(httptest.NewRecorder(), &http.Request{})
98 // Make sure the handler starts before we initiate the
99 // next request, but don't let it finish yet.
102 for i := 0; i < 10; i++ {
103 h.okToProceed <- struct{}{}