Skip to content

xuender/limit

Repository files navigation

Limit

Go Report Card tag Go Version GoDoc Build Status Coverage License

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.

💡 Usage

You can import limit using:

import "github.com/xuender/limit"

Async

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]

Sync

start := time.Now()
limiter := limit.NewSync(10, time.Second)

_ = limiter.Wait()
_ = limiter.Wait()
_ = limiter.Wait()

fmt.Println(time.Since(start))

// Output:
// 300ms

[play]

rdb.Distributed

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

[play]

Handler

http.Handle("/", limit.FuncHandler(1000, time.Second*10,
  func(w http.ResponseWriter, r *http.Request) {
    _, _ = io.WriteString(w, "PONG")
  },
))
http.ListenAndServe(":8080", nil)

[play]

😁 Cover

codecov

📝 License

© ender, 2022~time.Now

MIT License