Skip to content

Commit

Permalink
example(request): set rate limiter for request
Browse files Browse the repository at this point in the history
  • Loading branch information
ahuigo committed Oct 17, 2023
1 parent 58e3d0f commit 6e947c7
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
49 changes: 49 additions & 0 deletions examples/req_rate_test.go
@@ -0,0 +1,49 @@
package examples

import (
"net/http"
"strconv"
"testing"
"time"

"github.com/go-resty/resty/v3"
"golang.org/x/time/rate"
)

func TestRateLimiter(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()

// Test a burst with a valid capacity and then a consecutive request that must fail.

// Allow a rate of 1 every 100 ms but also allow bursts of 10 requests.
client := resty.New().SetRateLimiter(rate.NewLimiter(rate.Every(100*time.Millisecond), 10))

// Execute a burst of 10 requests.
for i := 0; i < 10; i++ {
resp, err := client.R().
SetQueryParam("request_no", strconv.Itoa(i)).Get(ts.URL + "/get")
assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
}
// Next request issued directly should fail because burst of 10 has been consumed.
{
_, err := client.R().
SetQueryParam("request_no", strconv.Itoa(11)).Get(ts.URL + "/get")
assertErrorIs(t, resty.ErrRateLimitExceeded, err)
}

// Test continues request at a valid rate

// Allow a rate of 1 every ms with no burst.
client = resty.New().SetRateLimiter(rate.NewLimiter(rate.Every(1*time.Millisecond), 1))

// Sending requests every ms+tiny delta must succeed.
for i := 0; i < 100; i++ {
resp, err := client.R().
SetQueryParam("request_no", strconv.Itoa(i)).Get(ts.URL + "/get")
assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
time.Sleep(1*time.Millisecond + 100*time.Microsecond)
}
}
2 changes: 2 additions & 0 deletions examples/server_test.go
Expand Up @@ -38,6 +38,7 @@ func createHttpbinServer(tlsCert int) (ts *httptest.Server) {
case path == "/cookie/count":
cookieHandler(w, r)
default:
w.WriteHeader(404)
_, _ = w.Write([]byte("404 " + path))
}
}, tlsCert)
Expand Down Expand Up @@ -148,6 +149,7 @@ func cookieHandler(w http.ResponseWriter, r *http.Request) {
buf, _ := json.Marshal(m)
_, _ = w.Write(buf)
default:
w.WriteHeader(404)
_, _ = w.Write([]byte("404 " + r.URL.Path))
}
}
Expand Down

0 comments on commit 6e947c7

Please sign in to comment.