mirror of
https://github.com/TeaOSLab/EdgeAPI.git
synced 2025-12-10 04:00:24 +08:00
实现API节点下载更新IP库、基本的分析函数
This commit is contained in:
56
internal/iplibrary/library_ip2region.go
Normal file
56
internal/iplibrary/library_ip2region.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package iplibrary
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
"github.com/lionsoul2014/ip2region/binding/golang/ip2region"
|
||||
)
|
||||
|
||||
type IP2RegionLibrary struct {
|
||||
db *ip2region.Ip2Region
|
||||
}
|
||||
|
||||
func (this *IP2RegionLibrary) Load(dbPath string) error {
|
||||
db, err := ip2region.New(dbPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
this.db = db
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (this *IP2RegionLibrary) Lookup(ip string) (*Result, error) {
|
||||
if this.db == nil {
|
||||
return nil, errors.New("library has not been loaded")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
// 防止panic发生
|
||||
err := recover()
|
||||
if err != nil {
|
||||
logs.Println("[IP2RegionLibrary]panic: " + fmt.Sprintf("%#v", err))
|
||||
}
|
||||
}()
|
||||
|
||||
info, err := this.db.MemorySearch(ip)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Result{
|
||||
CityId: info.CityId,
|
||||
Country: info.Country,
|
||||
Region: info.Region,
|
||||
Province: info.Province,
|
||||
City: info.City,
|
||||
ISP: info.ISP,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (this *IP2RegionLibrary) Close() {
|
||||
if this.db != nil {
|
||||
this.db.Close()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user