wp-go/app/middleware/flowLimit.go

39 lines
1.0 KiB
Go
Raw Normal View History

2022-09-29 09:23:02 +00:00
package middleware
import (
2023-01-21 11:31:23 +00:00
"github.com/fthvgb1/wp-go/helper/number"
"github.com/fthvgb1/wp-go/safety"
2022-09-29 09:23:02 +00:00
"github.com/gin-gonic/gin"
"net/http"
"sync/atomic"
"time"
)
2022-11-16 02:51:39 +00:00
func FlowLimit(maxRequestSleepNum, maxRequestNum int64, sleepTime []time.Duration) (func(ctx *gin.Context), func(int64, int64, []time.Duration)) {
2022-09-29 09:23:02 +00:00
var flow int64
2022-11-16 02:51:39 +00:00
s := safety.Var[[]time.Duration]{}
s.Store(sleepTime)
fn := func(sleepNum, maxNum int64, st []time.Duration) {
atomic.StoreInt64(&maxRequestSleepNum, sleepNum)
atomic.StoreInt64(&maxRequestNum, maxNum)
2022-11-16 02:51:39 +00:00
s.Store(st)
}
2022-09-29 09:23:02 +00:00
return func(c *gin.Context) {
2022-10-14 09:15:43 +00:00
n := atomic.LoadInt64(&flow)
2025-03-16 14:11:28 +00:00
if n >= atomic.LoadInt64(&maxRequestSleepNum) && n < atomic.LoadInt64(&maxRequestNum) {
2022-11-16 02:51:39 +00:00
ss := s.Load()
2023-01-21 11:31:23 +00:00
t := number.Rand(ss[0], ss[1])
2022-10-14 09:15:43 +00:00
time.Sleep(t)
2025-03-16 14:11:28 +00:00
} else if n >= atomic.LoadInt64(&maxRequestNum) {
2022-10-04 03:13:14 +00:00
c.String(http.StatusForbidden, "请求太多了,服务器君表示压力山大==!, 请稍后访问")
2022-09-29 09:23:02 +00:00
c.Abort()
return
}
2022-10-14 09:15:43 +00:00
atomic.AddInt64(&flow, 1)
defer func() {
atomic.AddInt64(&flow, -1)
}()
2022-09-29 09:23:02 +00:00
c.Next()
2022-11-16 02:51:39 +00:00
}, fn
2022-09-29 09:23:02 +00:00
}