31 lines
603 B
Go
31 lines
603 B
Go
package middleware
|
|
|
|
import (
|
|
"github.com/didip/tollbooth"
|
|
"github.com/didip/tollbooth/limiter"
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
)
|
|
|
|
var limit *limiter.Limiter
|
|
|
|
func init() {
|
|
limit = tollbooth.NewLimiter(5, nil)
|
|
}
|
|
|
|
func RateLimiterHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
httpError := tollbooth.LimitByRequest(limit, c.Writer, c.Request)
|
|
if httpError != nil {
|
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
|
"code": http.StatusTooManyRequests,
|
|
"type": "no",
|
|
"message": "click too fast",
|
|
"data": nil,
|
|
})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|