Browse Source

update

master
evanchen333 6 months ago
parent
commit
04e86511dc
  1. 25
      README.md
  2. 2
      limiter.go
  3. 0
      limiter_test.go

25
README.md

@ -7,10 +7,10 @@ The counting of the rate is based on the hits within the past **interval**
Run `go run example/main.go` and `curl http://localhost:8080/hit`.
The
## Limiter Usage
### As An Endpoint
```go
var l *limiter.Limiter
@ -27,3 +27,26 @@ func main() {
http.ListenAndServe(":8080", nil)
}
```
### As Custom Gin Middleware
```go
func RateLimit() gin.HandlerFunc {
l := limiter.Default()
return func(c *gin.Context) {
ip := c.Header.Get("X-Real-Ip")
if ip == "" {
ip = c.Header.Get("X-Forwarded-For")
}
if ip == "" {
ip, _, _ = net.SplitHostPort(c.RemoteAddr)
}
rate, err := l.HitOrError(ip)
if err != nil {
c.String(500, fmt.Sprintf("error: %s", err))
} else {
c.Next()
}
}
}
```

2
limiter.go

@ -56,6 +56,8 @@ func (l *Limiter) Init() {
//Rate within interval
func (l *Limiter) Rate(ip string) (rate int, err error) {
l.Mux.Lock()
defer l.Mux.Unlock()
row := l.Store.QueryRow(
"select COUNT(*) from hit where ip = ? and hit_time > ?",
ip,

0
limter_test.go → limiter_test.go

Loading…
Cancel
Save