simplerate
simplerate is a small, in-memory rate limiter for Go. It limits how often an action can be performed within a given time interval.
Installation
Replace the module path with your own repository if needed.
go get github.com/aredoff/simplerate
Usage
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/aredoff/simplerate"
)
func main() {
// Allow up to 5 events per second.
lim := simplerate.New(5, time.Second)
for i := 0; i < 10; i++ {
lim.Wait()
fmt.Println("event", i)
}
}
API
-
New(limit int, interval time.Duration) Limiter
Creates a new limiter that allows up to limit events per interval.
-
Limiter.Try() (ok bool, remaining time.Duration)
Attempts to perform an action. Returns true if allowed, or false and the remaining time until the next action is allowed.
-
Limiter.Wait()
Blocks until the action is allowed.
-
Limiter.WaitWithContext(ctx context.Context) error
Blocks until the action is allowed or the context is canceled.
Notes
- This limiter is in-memory and not distributed.
- It is safe for concurrent use from multiple goroutines.