feat: sync httpdns sdk/platform updates without large binaries
This commit is contained in:
@@ -7,9 +7,7 @@ import (
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MaxMindReader MaxMind GeoIP2 Reader
|
||||
@@ -19,6 +17,9 @@ type MaxMindReader struct {
|
||||
meta *Meta
|
||||
initialized bool
|
||||
mutex sync.RWMutex
|
||||
|
||||
// 临时文件路径,Destroy 时自动清理
|
||||
tmpFiles []string
|
||||
}
|
||||
|
||||
// NewMaxMindReader 创建 MaxMind Reader
|
||||
@@ -66,27 +67,9 @@ func NewMaxMindReaderFromBytes(cityDBData, asnDBData []byte) (*MaxMindReader, er
|
||||
return nil, fmt.Errorf("city database data is required")
|
||||
}
|
||||
|
||||
// 创建临时文件,使用更唯一的文件名避免冲突
|
||||
tmpDir := os.TempDir()
|
||||
pid := os.Getpid()
|
||||
// 使用时间戳增加唯一性,避免同一进程多次调用时的冲突
|
||||
timestamp := time.Now().UnixNano()
|
||||
cityTmpFile := filepath.Join(tmpDir, fmt.Sprintf("geolite2-city-%d-%d.mmdb", pid, timestamp))
|
||||
asnTmpFile := filepath.Join(tmpDir, fmt.Sprintf("geolite2-asn-%d-%d.mmdb", pid, timestamp))
|
||||
|
||||
// 如果临时文件已存在,先删除(可能是之前崩溃留下的)
|
||||
os.Remove(cityTmpFile)
|
||||
os.Remove(asnTmpFile)
|
||||
|
||||
// 写入 City 数据库到临时文件
|
||||
if err := os.WriteFile(cityTmpFile, cityDBData, 0644); err != nil {
|
||||
return nil, fmt.Errorf("write city database to temp file failed: %w", err)
|
||||
}
|
||||
|
||||
// 打开 City 数据库
|
||||
db, err := geoip2.Open(cityTmpFile)
|
||||
// 直接从内存字节加载,避免在 /tmp 持续生成 mmdb 临时文件。
|
||||
db, err := geoip2.FromBytes(cityDBData)
|
||||
if err != nil {
|
||||
os.Remove(cityTmpFile)
|
||||
return nil, fmt.Errorf("open MaxMind city database failed: %w", err)
|
||||
}
|
||||
|
||||
@@ -94,16 +77,11 @@ func NewMaxMindReaderFromBytes(cityDBData, asnDBData []byte) (*MaxMindReader, er
|
||||
db: db,
|
||||
}
|
||||
|
||||
// 写入并打开 ASN 数据库(可选)
|
||||
// 加载 ASN 数据库(可选)
|
||||
if len(asnDBData) > 0 {
|
||||
if err := os.WriteFile(asnTmpFile, asnDBData, 0644); err == nil {
|
||||
dbASN, err := geoip2.Open(asnTmpFile)
|
||||
if err == nil {
|
||||
reader.dbASN = dbASN
|
||||
} else {
|
||||
// ASN 数据库打开失败,清理临时文件但不影响主功能
|
||||
os.Remove(asnTmpFile)
|
||||
}
|
||||
dbASN, err := geoip2.FromBytes(asnDBData)
|
||||
if err == nil {
|
||||
reader.dbASN = dbASN
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,7 +152,7 @@ func (this *MaxMindReader) Meta() *Meta {
|
||||
return this.meta
|
||||
}
|
||||
|
||||
// Destroy 销毁 Reader
|
||||
// Destroy 销毁 Reader 并清理临时文件
|
||||
func (this *MaxMindReader) Destroy() {
|
||||
this.mutex.Lock()
|
||||
defer this.mutex.Unlock()
|
||||
@@ -187,6 +165,10 @@ func (this *MaxMindReader) Destroy() {
|
||||
this.dbASN.Close()
|
||||
this.dbASN = nil
|
||||
}
|
||||
for _, f := range this.tmpFiles {
|
||||
os.Remove(f)
|
||||
}
|
||||
this.tmpFiles = nil
|
||||
this.initialized = false
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user