forked from MartialBE/one-hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-limit.go
45 lines (37 loc) · 918 Bytes
/
api-limit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package middleware
import (
"fmt"
"net/http"
"one-api/common/config"
"one-api/model"
"time"
"github.com/gin-gonic/gin"
)
const (
LIMIT_KEY = "api-limiter:%d"
INTERNAL = 1 * time.Minute
RATE_LIMIT_EXCEEDED_MSG = "您的速率达到上限,请稍后再试。"
SERVER_ERROR_MSG = "Server error"
)
func DynamicRedisRateLimiter() gin.HandlerFunc {
return func(c *gin.Context) {
if !config.RedisEnabled {
c.Next()
return
}
userID := c.GetInt("id")
userGroup := c.GetString("group")
// API速率限制
limiter := model.GlobalUserGroupRatio.GetAPILimiter(userGroup)
if limiter == nil {
abortWithMessage(c, http.StatusForbidden, "API requests are not allowed")
return
}
key := fmt.Sprintf(LIMIT_KEY, userID)
if !limiter.Allow(key) {
abortWithMessage(c, http.StatusTooManyRequests, RATE_LIMIT_EXCEEDED_MSG)
return
}
c.Next()
}
}