wp-go/middleware/flowLimit.go

98 lines
2.0 KiB
Go
Raw Permalink Normal View History

2022-09-29 09:23:02 +00:00
package middleware
import (
"github.com/gin-gonic/gin"
"math/rand"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
type IpLimitMap struct {
2022-10-09 15:22:18 +00:00
mux *sync.Mutex
m map[string]*int64
singleIpSearchNum int64
2022-09-29 09:23:02 +00:00
}
2022-10-09 15:22:18 +00:00
func FlowLimit(maxRequestSleepNum, maxRequestNum, singleIpSearchNum int64, sleepTime []time.Duration) func(ctx *gin.Context) {
2022-09-29 09:23:02 +00:00
var flow int64
rand.Seed(time.Now().UnixNano())
randFn := func(start, end time.Duration) time.Duration {
end++
return time.Duration(rand.Intn(int(end-start)) + int(start))
}
m := IpLimitMap{
2022-10-09 15:22:18 +00:00
mux: &sync.Mutex{},
m: make(map[string]*int64),
singleIpSearchNum: singleIpSearchNum,
2022-09-29 09:23:02 +00:00
}
statPath := map[string]struct{}{
"wp-includes": {},
"wp-content": {},
"favicon.ico": {},
}
return func(c *gin.Context) {
f := strings.Split(strings.TrimLeft(c.FullPath(), "/"), "/")
_, ok := statPath[f[0]]
if len(f) > 0 && ok {
c.Next()
return
}
2022-10-02 02:58:48 +00:00
s := false
2022-09-29 09:25:15 +00:00
ip := c.ClientIP()
2022-10-02 02:58:48 +00:00
defer m.searchLimit(false, c, ip, f, &s)
if m.searchLimit(true, c, ip, f, &s) {
2022-09-29 09:23:02 +00:00
c.Abort()
return
}
atomic.AddInt64(&flow, 1)
2022-10-02 02:58:48 +00:00
defer func() {
atomic.AddInt64(&flow, -1)
}()
2022-10-09 15:22:18 +00:00
if flow >= maxRequestSleepNum && flow <= maxRequestNum {
t := randFn(sleepTime[0], sleepTime[1])
2022-09-29 09:23:02 +00:00
time.Sleep(t)
2022-10-09 15:22:18 +00:00
} else if flow > maxRequestNum {
2022-10-04 03:13:14 +00:00
c.String(http.StatusForbidden, "请求太多了,服务器君表示压力山大==!, 请稍后访问")
2022-09-29 09:23:02 +00:00
c.Abort()
2022-10-02 02:58:48 +00:00
2022-09-29 09:23:02 +00:00
return
}
c.Next()
2022-10-02 02:58:48 +00:00
}
2022-09-29 09:23:02 +00:00
}
2022-10-02 02:58:48 +00:00
func (m *IpLimitMap) searchLimit(start bool, c *gin.Context, ip string, f []string, s *bool) (isForbid bool) {
2022-09-29 09:23:02 +00:00
if f[0] == "" && c.Query("s") != "" {
2022-10-02 02:58:48 +00:00
if start {
2022-09-29 09:23:02 +00:00
i, ok := m.m[ip]
2022-10-02 02:58:48 +00:00
if !ok {
m.mux.Lock()
i = new(int64)
m.m[ip] = i
m.mux.Unlock()
2022-09-29 09:23:02 +00:00
}
2022-10-09 15:22:18 +00:00
if m.singleIpSearchNum > 0 && *i >= m.singleIpSearchNum {
2022-10-02 02:58:48 +00:00
isForbid = true
return
}
*s = true
atomic.AddInt64(i, 1)
return
}
i, ok := m.m[ip]
if ok && *s && *i > 0 {
atomic.AddInt64(i, -1)
if *i == 0 {
2022-09-29 09:23:02 +00:00
m.mux.Lock()
delete(m.m, ip)
m.mux.Unlock()
}
}
}
return
}