https://github.com/twiny/limiter
IP based rate limiter
https://github.com/twiny/limiter
go golang http limiter rate-limiter rest-api
Last synced: 10 months ago
JSON representation
IP based rate limiter
- Host: GitHub
- URL: https://github.com/twiny/limiter
- Owner: twiny
- License: mit
- Created: 2021-08-13T09:04:09.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2021-08-23T21:40:15.000Z (over 4 years ago)
- Last Synced: 2025-02-09T17:42:34.728Z (12 months ago)
- Topics: go, golang, http, limiter, rate-limiter, rest-api
- Language: Go
- Homepage:
- Size: 4.88 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## HTTP Rate Limiter
rate limit HTTP requests based on client IP address.
### Install
`go get github.com/twiny/limiter`
### Example
```go
import "github.com/twiny/limiter"
// App
type App struct{
... ...
limiter *limiter.Limiter
... ...
}
// RateLimit
func (a *App) RateAllow(ip string) bool {
limit, found := a.limiter.Get(ip)
if !found {
a.limiter.Set(ip)
return true
}
return limit.Allow()
}
```
```go
// HTTPHandler
type HTTPHandler struct{
... ...
app *App
... ...
}
// rate limit
func (route *HTTPHandler) ratelimit(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
var remoteIP string
remoteIP = r.RemoteAddr
if strings.ContainsRune(r.RemoteAddr, ':') {
remoteIP, _, _ = net.SplitHostPort(r.RemoteAddr)
}
if !route.app.RateAllow(remoteIP) {
http.Error(w,"going too fast - slow down", http.StatusTooManyRequests)
return
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
```