add time check for not realtime clear online ip

This commit is contained in:
yuzuki999 2023-05-19 08:47:28 +08:00
parent 30549a4ad1
commit 8890b566d5

View File

@ -2,6 +2,7 @@ package limiter
import ( import (
"sync" "sync"
"time"
) )
type ConnLimiter struct { type ConnLimiter struct {
@ -46,7 +47,7 @@ func (c *ConnLimiter) AddConnCount(user string, ip string, isTcp bool) (limit bo
ipMap.Store(ip, 1) ipMap.Store(ip, 1)
} }
} else { } else {
ipMap.Store(ip, struct{}{}) ipMap.Store(ip, time.Now())
} }
// check user online ip // check user online ip
if v, ok := c.ip.LoadOrStore(user, ipMap); ok { if v, ok := c.ip.LoadOrStore(user, ipMap); ok {
@ -60,6 +61,8 @@ func (c *ConnLimiter) AddConnCount(user string, ip string, isTcp bool) (limit bo
// count add // count add
ips.Store(ip, online.(int)+2) ips.Store(ip, online.(int)+2)
} }
} else {
ips.Store(ip, time.Now())
} }
} else { } else {
// not online ip // not online ip
@ -81,7 +84,7 @@ func (c *ConnLimiter) AddConnCount(user string, ip string, isTcp bool) (limit bo
ips.Store(ip, 1) ips.Store(ip, 1)
} }
} else { } else {
ips.Store(ip, struct{}{}) ips.Store(ip, time.Now())
} }
} }
} }
@ -130,14 +133,18 @@ func (c *ConnLimiter) ClearOnlineIP() {
c.ip.Range(func(_, v any) bool { c.ip.Range(func(_, v any) bool {
userIp := v.(*sync.Map) userIp := v.(*sync.Map)
userIp.Range(func(ip, v any) bool { userIp.Range(func(ip, v any) bool {
if c.realtime { if _, ok := v.(int); ok {
// clear not realtime ip if v.(int) == 1 {
userIp.Delete(ip) // clear packet ip for realtime
userIp.Delete(ip)
}
return true return true
} } else {
if v.(int) == 1 { // clear ip for not realtime
// clear packet ip for realtime if v.(time.Time).Before(time.Now().Add(time.Minute)) {
userIp.Delete(ip) // 1 minute no active
userIp.Delete(ip)
}
} }
return true return true
}) })