优化白名单
This commit is contained in:
50
whitelist.go
Normal file
50
whitelist.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
whiteList = make(map[string]struct{})
|
||||
whiteListLock = sync.RWMutex{}
|
||||
)
|
||||
|
||||
func LoadWhiteList(filename string) error {
|
||||
// 如果文件不存在,直接返回 nil 表示无需加载
|
||||
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
||||
log.Printf(" 白名单文件 %s 不存在,跳过加载。", filename)
|
||||
return nil
|
||||
}
|
||||
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
tempList := make(map[string]struct{})
|
||||
|
||||
for scanner.Scan() {
|
||||
ip := strings.TrimSpace(scanner.Text())
|
||||
if ip != "" {
|
||||
tempList[ip] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 用写锁更新全局白名单
|
||||
whiteListLock.Lock()
|
||||
whiteList = tempList
|
||||
whiteListLock.Unlock()
|
||||
|
||||
log.Println("白名单已加载完成")
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user