api-server/api/network/service/ip_service.go
2024-09-25 16:35:07 +08:00

55 lines
1.1 KiB
Go

package service
import (
"api/api/network/model"
"fmt"
"github.com/lionsoul2014/ip2region/binding/golang/xdb"
"log"
"strings"
)
var (
searcher *xdb.Searcher
)
type IpService struct{}
func init() {
var dbPath = "config/google.xdb"
// 1、从 dbPath 加载整个 xdb 到内存
cBuff, err := xdb.LoadContentFromFile(dbPath)
if err != nil {
fmt.Printf("failed to load content from `%s`: %s\n", dbPath, err)
if err != nil {
log.Panic("dbPath初始化失败: ", err)
}
}
// 2、用全局的 cBuff 创建完全基于内存的查询对象。
searcher, err = xdb.NewWithBuffer(cBuff)
if err != nil {
fmt.Printf("failed to create searcher with content: %s\n", err)
if err != nil {
log.Panic("searcher初始化失败: ", err)
}
}
}
// GetIpInfo 获取IP信息
func (*IpService) GetIpInfo(ip string) (model.IpInfo, error) {
region, err := searcher.SearchByStr(ip)
if err != nil {
return model.IpInfo{}, err
}
info := strings.Split(region, "|")
var ipInfo = model.IpInfo{
IP: ip,
Country: info[0],
Region: info[1],
Province: info[2],
City: info[3],
ISP: info[4],
}
return ipInfo, nil
}