26 lines
465 B
Go
26 lines
465 B
Go
package middleware
|
|
|
|
import (
|
|
"blog/pkg/app"
|
|
"blog/pkg/errorcode"
|
|
"blog/pkg/limiter"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func RateLimiter(l limiter.LimiterIface) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
key := l.Key(c)
|
|
if bucket, ok := l.GetBucket(key); ok {
|
|
count := bucket.TakeAvailable(1)
|
|
if count == 0 {
|
|
response := app.NewResponse(c)
|
|
response.ToErrorResponse(errorcode.TooManyRequests)
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|