A Redis-backed rate limiter in Go
A Redis-backed Rate Limiter for Go
Branch | Go Get Command | Client Version | - |
---|---|---|---|
v2 | go get gopkg.in/etcinit/speedbump.v2 |
gopkg.in/redis.v5 |
Link |
v1, master | go get gopkg.in/etcinit/speedbump.v1 |
gopkg.in/redis.v3 |
Link |
v0 | go get gopkg.in/etcinit/speedbump.v0 |
gopkg.in/redis.v2 |
Link |
$ go get github.com/etcinit/speedbump
package main
import (
"fmt"
"time"
"github.com/etcinit/speedbump"
"gopkg.in/redis.v5"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
hasher := speedbump.PerSecondHasher{}
// Here we create a limiter that will only allow 5 requests per second
limiter := speedbump.NewLimiter(client, hasher, 5)
for {
// This example has a hardcoded IP, but you would replace it with the IP
// of a client on a real case.
success, err := limiter.Attempt("127.0.0.1")
if err != nil {
panic(err)
}
if success {
fmt.Println("Successful!")
} else {
fmt.Println("Limited! :(")
}
time.Sleep(time.Millisecond * time.Duration(100))
}
}
Successful!
Successful!
Successful!
Successful!
Successful!
Successful!
Limited! :(
Limited! :(
Limited! :(
Limited! :(
Limited! :(
Successful!
Successful!
Successful!
Successful!
Successful!
Successful!
Limited! :(
Limited! :(
Limited! :(
Limited! :(
Successful!
Successful!
...