Golang channel based rate limiter.
- supports asynchronous and synchronous calls.
- simple middleware to rate limit HTTP requests.
- requests that may timeout will returns an error immediately.
- call order.
- redis based distributed limiter.
You can import limit using:
import "github.com/xuender/limit"
start := time.Now()
limiter := limit.NewAsync(10, time.Second, func(num int) {
fmt.Println(time.Since(start), num)
})
_ = limiter.Add(1)
_ = limiter.Add(2)
_ = limiter.Add(3)
time.Sleep(time.Second)
// Output:
// 100ms 1
// 200ms 2
// 300ms 3
[play]
start := time.Now()
limiter := limit.NewSync(10, time.Second)
_ = limiter.Wait()
_ = limiter.Wait()
_ = limiter.Wait()
fmt.Println(time.Since(start))
// Output:
// 300ms
[play]
redis based distributed limiter.
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
start := time.Now()
limiter := rdb.NewDistributed(client, "key", 1000, time.Second)
_ = limiter.Wait()
_ = limiter.Wait()
_ = limiter.Wait()
fmt.Println(time.Since(start))
http.Handle("/", limit.FuncHandler(1000, time.Second*10,
func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "PONG")
},
))
http.ListenAndServe(":8080", nil)
[play]
© ender, 2022~time.Now