Quickstart Guide
This guide will walk you through setting up rate limiting in your Go application in under 5 minutes.
Step 1: Initialize a Storage Driver
Section titled “Step 1: Initialize a Storage Driver”Every distlimit instance requires a storage backend driver. For local applications or single-instance microservices, initialize the 64-Sharded Memory Driver:
package main
import ( "context" "time"
"github.com/balramadan/distlimit/driver/memory")
func main() { // Initialize In-Memory Driver with a 5-minute key TTL for background cleanup memDriver := memory.New(5 * time.Minute) defer func() { _ = memDriver.Close(context.Background()) }()}Step 2: Configure the Rate Limiter
Section titled “Step 2: Configure the Rate Limiter”Combine your storage driver with rate limiting rules (Limit, Window, and Algorithm Strategy) using functional options:
import ( "time"
"github.com/balramadan/distlimit" "github.com/balramadan/distlimit/algorithm/slidingcounter" "github.com/balramadan/distlimit/driver/memory")
// Configure a Limiter: 100 requests per 1 minute window using Sliding Window Counterlimiter, err := distlimit.New( memDriver, distlimit.WithLimit(100), distlimit.WithWindow(1*time.Minute), distlimit.WithAlgorithm(slidingcounter.New()),)if err != nil { panic(err)}Step 3: Evaluate Rate Limits in Business Logic
Section titled “Step 3: Evaluate Rate Limits in Business Logic”Use AllowKey to check if a specific client key (IP address, User ID, or API Key) is permitted to execute:
ctx := context.Background()clientKey := "user_id:98765"
res, err := limiter.AllowKey(ctx, clientKey)if err != nil { log.Printf("Rate limit evaluation failed: %v", err)}
if res.Allowed { fmt.Printf("Request permitted! Remaining quota: %d\n", res.Remaining)} else { fmt.Printf("Rate limit exceeded! Retry after: %v\n", res.ResetIn)}Step 4: Protect HTTP Endpoints via Middleware
Section titled “Step 4: Protect HTTP Endpoints via Middleware”Protect your Web API endpoints automatically using distlimit middleware adapters:
package main
import ( "net/http" "time"
"github.com/balramadan/distlimit" "github.com/balramadan/distlimit/algorithm/tokenbucket" "github.com/balramadan/distlimit/driver/memory" distlimitnethttp "github.com/balramadan/distlimit/middleware/nethttp")
func main() { memDriver := memory.New(5 * time.Minute) defer memDriver.Close(nil)
limiter, _ := distlimit.New( memDriver, distlimit.WithLimit(100), distlimit.WithWindow(1*time.Minute), distlimit.WithAlgorithm(tokenbucket.New()), )
mux := http.NewServeMux()
apiHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"status":"success","data":"Hello World"}`)) })
protectedMux := distlimitnethttp.New( limiter, distlimitnethttp.WithTrustedProxies([]string{"10.0.0.0/8"}), )(apiHandler)
mux.Handle("/api/v1/data", protectedMux) http.ListenAndServe(":8080", mux)}