Go package that implements IP-based token buckets for rate limiting
alimiracle 8187ea5567 move to codeberg | 5 months ago | |
---|---|---|
API_Documentation.md | 1 year ago | |
README.md | 5 months ago | |
bucket_manager.go | 1 year ago | |
bucket_manager_test.go | 1 year ago | |
go.mod | 1 year ago | |
golimiter.go | 1 year ago | |
golimiter_test.go | 1 year ago |
this project has been archived and migrated to codeberg. To access the project on codeberg,
GoLimiter is a Go package that implements IP-based token buckets for rate limiting. It provides a simple and efficient way to control the rate of requests from different IP addresses.
To use GoLimiter in your Go project, you can simply import it using the following import path:
import "notabug.org/alimiracle/golimiter"
Here's a quick example of how to use GoLimiter to perform IP-based rate limiting in your Go application:
package main
import (
"fmt"
"sync"
"time"
"notabug.org/alimiracle/golimiter"
)
func main() {
// Create a new token bucket manager
limiter := golimiter.NewTokenBucketManager()
// Start a cleanup task to remove expired token buckets
go limiter.StartCleanupTask(5 * time.Second) // Run cleanup task every 5 seconds
// Simulate requests from different IPs
ips := []string{"192.168.1.1", "192.168.1.2", "192.168.1.3"}
var wg sync.WaitGroup
for _, ip := range ips {
wg.Add(1)
go func(ip string) {
defer wg.Done()
// Get or create a token bucket for the IP
tb, err := limiter.CreateTokenBucket(ip, 10, 4, 10)
if err != nil {
fmt.Printf("Error creating token bucket for %s: %s\n", ip, err)
return
}
for i := 0; i < 10; i++ {
// Try to take a token from the token bucket
if tb.TakeToken() {
fmt.Printf("Request from %s processed\n", ip)
} else {
fmt.Printf("Request from %s dropped\n", ip)
}
// Introduce a delay between requests
time.Sleep(time.Second)
}
}(ip)
}
// Wait for all goroutines to finish
wg.Wait()
}
Contributions to GoLimiter are welcome! Feel free to submit pull requests or open issues if you find bugs, want to improve the code, or have suggestions for new features.
This project is licensed under the LGPL License.