-
Notifications
You must be signed in to change notification settings - Fork 472
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7ebcd0f
commit 4a3282c
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// Copyright 2024, Chef. All rights reserved. | ||
// https://github.com/q191201771/lal | ||
// | ||
// Use of this source code is governed by a MIT-style license | ||
// that can be found in the License file. | ||
// | ||
// Author: Chef (191201771@qq.com) | ||
|
||
package logic | ||
|
||
import ( | ||
"sync" | ||
"time" | ||
) | ||
|
||
type IpBlacklist struct { | ||
mu sync.Mutex | ||
ips map[string]int64 // TODO(chef): 优化性能 202405 | ||
} | ||
|
||
func (l *IpBlacklist) Add(ip string, durationSec int) { | ||
l.mu.Lock() | ||
defer l.mu.Unlock() | ||
|
||
if l.ips == nil { | ||
l.ips = make(map[string]int64) | ||
} | ||
|
||
until := time.Now().Unix() + int64(durationSec) | ||
l.ips[ip] = until | ||
} | ||
|
||
func (l *IpBlacklist) Has(ip string) bool { | ||
l.mu.Lock() | ||
defer l.mu.Unlock() | ||
|
||
l.eraseStale() | ||
|
||
_, ok := l.ips[ip] | ||
return ok | ||
} | ||
|
||
func (l *IpBlacklist) eraseStale() { | ||
now := time.Now().Unix() | ||
|
||
stales := make(map[string]struct{}) | ||
|
||
for ip, until := range l.ips { | ||
if until < now { | ||
stales[ip] = struct{}{} | ||
} | ||
} | ||
|
||
for ip := range stales { | ||
Log.Debugf("erase ip from blacklist. ip=%s", ip) | ||
delete(l.ips, ip) | ||
} | ||
} |