You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.4 KiB
73 lines
1.4 KiB
package ip2region_v2
|
|
|
|
import (
|
|
_ "embed"
|
|
"go.dtapp.net/gostring"
|
|
"net"
|
|
)
|
|
|
|
//go:embed ip2region.xdb
|
|
var cBuff []byte
|
|
|
|
type Client struct {
|
|
db *Searcher
|
|
}
|
|
|
|
func New() (*Client, error) {
|
|
|
|
var err error
|
|
c := &Client{}
|
|
|
|
// 1、从 dbPath 加载整个 xdb 到内存
|
|
|
|
// 2、用全局的 cBuff 创建完全基于内存的查询对象。
|
|
c.db, err = NewWithBuffer(cBuff)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return c, err
|
|
}
|
|
|
|
// Result 返回
|
|
type Result struct {
|
|
Ip string `json:"ip,omitempty"` // 查询的ip地址
|
|
Country string `json:"country,omitempty"` // 国家
|
|
Province string `json:"province,omitempty"` // 省份
|
|
City string `json:"city,omitempty"` // 城市
|
|
Operator string `json:"operator,omitempty"` // 运营商
|
|
}
|
|
|
|
func (c *Client) Query(ipAddress net.IP) (result Result, err error) {
|
|
|
|
// 备注:并发使用,用整个 xdb 缓存创建的 searcher 对象可以安全用于并发。
|
|
|
|
str, err := c.db.SearchByStr(ipAddress.String())
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
|
|
split := gostring.Split(str, "|")
|
|
if len(split) <= 0 {
|
|
return Result{}, err
|
|
}
|
|
|
|
result.Ip = ipAddress.String()
|
|
|
|
result.Country = split[0]
|
|
result.Province = split[2]
|
|
if result.Province == "0" {
|
|
result.Province = ""
|
|
}
|
|
result.City = split[3]
|
|
if result.City == "0" {
|
|
result.City = ""
|
|
}
|
|
result.Operator = split[4]
|
|
if result.Operator == "0" {
|
|
result.Operator = ""
|
|
}
|
|
|
|
return result, err
|
|
}
|