https://github.com/xuender/limit
A Go rate limit implementation
https://github.com/xuender/limit
go golang limit limiter middleware rate-limit redis
Last synced: 2 months ago
JSON representation
A Go rate limit implementation
- Host: GitHub
- URL: https://github.com/xuender/limit
- Owner: xuender
- License: mit
- Created: 2022-11-24T06:12:03.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-08-05T09:02:01.000Z (10 months ago)
- Last Synced: 2025-02-09T19:40:50.650Z (4 months ago)
- Topics: go, golang, limit, limiter, middleware, rate-limit, redis
- Language: Go
- Homepage:
- Size: 63.5 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: History.md
- License: LICENSE
Awesome Lists containing this project
README
# Limit
[](https://goreportcard.com/report/github.com/xuender/limit)
[](https://github.com/xuender/limit/releases)

[](https://pkg.go.dev/github.com/xuender/limit)

[](https://codecov.io/gh/xuender/limit)
[](./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:
```go
import "github.com/xuender/limit"
```### Async
```go
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](https://go.dev/play/p/W9gYA_109Vz)]
### Sync
```go
start := time.Now()
limiter := limit.NewSync(10, time.Second)_ = limiter.Wait()
_ = limiter.Wait()
_ = limiter.Wait()fmt.Println(time.Since(start))
// Output:
// 300ms
```[[play](https://go.dev/play/p/ogcvT7o4ENI)]
### rdb.Distributed
redis based distributed limiter.
```go
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]](https://go.dev/play/p/SgAqdQRYhiK)
### Handler
```go
http.Handle("/", limit.FuncHandler(1000, time.Second*10,
func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "PONG")
},
))
http.ListenAndServe(":8080", nil)
```[[play](https://go.dev/play/p/oAoIZynIdkn)]
## 😁 Cover

## 📝 License
© ender, 2022~time.Now
[MIT License](https://github.com/xuender/limit/blob/master/LICENSE)