go-limite
//Install
go get -u github.com/yangxikun/gin-limit-by-key
// Note: You need to use gin-gonic
// Usage
import (
limit "github.com/yangxikun/gin-limit-by-key"
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
)
func main() {
r := gin.Default()
r.Use(limit.NewRateLimiter(func(c *gin.Context) string {
return c.ClientIP() // limit rate by client ip
}, func(c *gin.Context) (*rate.Limiter, time.Duration) {
// Burst rate -> 100 millisec
// 10 consecutive requests
// 5 seconds restriction
// limit 10 qps/clientIp and permit bursts of at most 10 tokens, and the limiter liveness time duration is 1 hour
return rate.NewLimiter(rate.Every(100*time.Millisecond), 10), time.Hour
}, func(c *gin.Context) {
c.AbortWithStatus(429) // handle exceed rate limit request
}))
r.GET("/", func(c *gin.Context) {})
r.Run(":8000")
}
MrNtlu