Documentation
¶
Overview ¶
Package ratelimiter provides a simple and efficient rate limiter for Go applications. It allows limiting the number of requests per time interval with thread-safe operations.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiter that allows a maximum number of requests per time interval. Tokens are refilled continuously (not in bursts at fixed boundaries), so it never allows more than 'rps' requests within any sliding window of length 'interval'. It is thread-safe and can be used concurrently from multiple goroutines.
func NewRateLimiter ¶
func NewRateLimiter(rps int, interval time.Duration) *RateLimiter
NewRateLimiter creates a new rate limiter with the specified requests per second limit and reset interval. The rate limiter will allow up to 'rps' requests within any sliding window of length 'interval'. The bucket starts full, so an initial burst of up to 'rps' requests is allowed immediately.
Example ¶
package main
import (
"fmt"
"time"
"github.com/TRAD3R/ratelimiter"
)
func main() {
// Создаем rate limiter с лимитом 10 запросов в секунду
rl := ratelimiter.NewRateLimiter(10, time.Second)
// Проверяем, разрешен ли запрос
if rl.AllowRequest() {
fmt.Println("Request allowed")
} else {
fmt.Println("Request denied")
}
}
Output: Request allowed
func (*RateLimiter) AllowRequest ¶
func (rl *RateLimiter) AllowRequest() bool
AllowRequest checks if a request is allowed according to the rate limit. It returns true if the request is allowed and consumes one token, or false if the rate limit has been exceeded.
Example ¶
package main
import (
"fmt"
"time"
"github.com/TRAD3R/ratelimiter"
)
func main() {
// Создаем rate limiter с лимитом 2 запроса в 100 миллисекунд
rl := ratelimiter.NewRateLimiter(2, 100*time.Millisecond)
// Первые два запроса должны быть разрешены
for i := 0; i < 2; i++ {
if rl.AllowRequest() {
fmt.Printf("Request %d: allowed\n", i+1)
}
}
// Третий запрос должен быть отклонен
if !rl.AllowRequest() {
fmt.Println("Request 3: denied (rate limit exceeded)")
}
// Ждем, пока накопится токен
time.Sleep(110 * time.Millisecond)
// После пополнения запрос снова разрешен
if rl.AllowRequest() {
fmt.Println("Request after refill: allowed")
}
}
Output: Request 1: allowed Request 2: allowed Request 3: denied (rate limit exceeded) Request after refill: allowed
func (*RateLimiter) CurrentState ¶
func (rl *RateLimiter) CurrentState() (int, time.Duration)
CurrentState returns the current state of the rate limiter. It returns the number of tokens currently available (rounded down) and the time remaining until the next token becomes available (0 if a token is already available).
Example ¶
package main
import (
"fmt"
"time"
"github.com/TRAD3R/ratelimiter"
)
func main() {
rl := ratelimiter.NewRateLimiter(5, time.Second)
// Делаем несколько запросов
rl.AllowRequest()
rl.AllowRequest()
// Проверяем текущее состояние
available, wait := rl.CurrentState()
fmt.Printf("Available tokens: %d\n", available)
if wait == 0 {
fmt.Println("Rate limiter is not blocking")
}
}
Output: Available tokens: 3 Rate limiter is not blocking
func (*RateLimiter) GetInterval ¶
func (rl *RateLimiter) GetInterval() time.Duration
GetInterval returns the configured reset interval. This method is primarily for testing purposes.
func (*RateLimiter) GetRPS ¶
func (rl *RateLimiter) GetRPS() int
GetRPS returns the configured requests per second limit. This method is primarily for testing purposes.
func (*RateLimiter) GetRetryAfter ¶
func (rl *RateLimiter) GetRetryAfter() time.Time
GetRetryAfter returns the time when the next token will become available. It returns the current time if a token is already available. This method is primarily for testing purposes.