I need to rate limit the requests to an API and I'm considering using the native golang.org/x/time/rate package for that purpose. In order to fiddling a little bit with its API and make sure that my assumptions are correct, I've created this tests, but it definitely seems that I'm missing something here:
package main
import (
"github.com/stretchr/testify/require"
"golang.org/x/time/rate"
"sync"
"testing"
)
func TestLimiter(t *testing.T) {
limiter := rate.NewLimiter(rate.Limit(5),1)
wg := sync.WaitGroup{}
successful := 0
for i:=1; i<=10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if limiter.Allow() {
successful++
}
}()
}
wg.Wait()
require.Equal(t, 5, successful)
// This test fails with
// Expected :5
// Actual :1
}
What is the explanation for why this is? Shouldn't the rate limiter allow 5 requests/second?