25 lines
450 B
Go
25 lines
450 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"code.yun.ink/pkg/limitx"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
)
|
||
|
|
|
||
|
|
func LimiterMiddleware() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
// 获取IP(待封装)
|
||
|
|
ipAddr := "127.0.0.1"
|
||
|
|
// c.Request.RemoteAddr
|
||
|
|
limiter := limitx.RateLimiter.GetLimiter(ipAddr)
|
||
|
|
if !limiter.Allow() {
|
||
|
|
c.JSON(400, gin.H{"code": 400, "message": "访问频率超出限制"})
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
} else {
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
return
|
||
|
|
}
|
||
|
|
}
|