Go package that implements IP-based token buckets for rate limiting

alimiracle 8187ea5567 move to codeberg 5 months ago
API_Documentation.md f41d22b294 update bucket_manager and retype the tests 1 year ago
README.md 8187ea5567 move to codeberg 5 months ago
bucket_manager.go 9a7588ab8f GetRemainingTokens returns the remaining token count for the specified IP address 1 year ago
bucket_manager_test.go 2e923fa0de TakeToken tries to retrieve a token from the bucket. Returns true if successful, false otherwise 1 year ago
go.mod 200907869e the pkg 1 year ago
golimiter.go 2e923fa0de TakeToken tries to retrieve a token from the bucket. Returns true if successful, false otherwise 1 year ago
golimiter_test.go f41d22b294 update bucket_manager and retype the tests 1 year ago

README.md

Important Note:

this project has been archived and migrated to codeberg. To access the project on codeberg,

visit this Link

GoLimiter:

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.

Installation:

To use GoLimiter in your Go project, you can simply import it using the following import path:

import "notabug.org/alimiracle/golimiter"

Usage:

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()
}

Contributing:

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.

License:

This project is licensed under the LGPL License.