wp-go/middleware/flowLimit.go

41 lines
897 B
Go
Raw Normal View History

2022-09-29 09:23:02 +00:00
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
"strings"
"sync/atomic"
"time"
)
2022-10-13 03:09:52 +00:00
func FlowLimit(maxRequestSleepNum, maxRequestNum int64, sleepTime []time.Duration) func(ctx *gin.Context) {
2022-09-29 09:23:02 +00:00
var flow int64
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-13 03:09:52 +00:00
2022-09-29 09:23:02 +00:00
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 {
2022-10-13 03:09:52 +00:00
//t := helper.RandNum(sleepTime[0], sleepTime[1])
//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()
return
}
c.Next()
}
}