/
uploadpic.go
43 lines (34 loc) · 932 Bytes
/
uploadpic.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
package server
import (
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"time"
"github.com/hoshinonyaruko/gensokyo-kook/config"
)
const (
MaximumImageSize = 10 * 1024 * 1024
AllowedUploadsPerMinute = 100
RequestInterval = time.Minute
)
type RateLimiter struct {
Counts map[string][]time.Time
}
// 频率限制器
func NewRateLimiter() *RateLimiter {
return &RateLimiter{
Counts: make(map[string][]time.Time),
}
}
// 检查是否超过调用频率限制
func (rl *RateLimiter) CheckAndUpdateRateLimit(ipAddress string) bool {
// 获取 MaxRequests 的当前值
maxRequests := config.GetImageLimitB()
now := time.Now()
rl.Counts[ipAddress] = append(rl.Counts[ipAddress], now)
// Remove expired entries
for len(rl.Counts[ipAddress]) > 0 && now.Sub(rl.Counts[ipAddress][0]) > RequestInterval {
rl.Counts[ipAddress] = rl.Counts[ipAddress][1:]
}
return len(rl.Counts[ipAddress]) <= maxRequests
}