74 lines
1.3 KiB
Go
74 lines
1.3 KiB
Go
package myip
|
|
|
|
import (
|
|
_ "embed"
|
|
"fmt"
|
|
"github.com/lionsoul2014/ip2region/binding/golang/xdb"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
searcher *xdb.Searcher
|
|
|
|
//go:embed ip2region.xdb
|
|
dbData []byte
|
|
)
|
|
|
|
func init() {
|
|
var err error
|
|
// 2、用全局的 cBuff 创建完全基于内存的查询对象。
|
|
searcher, err = xdb.NewWithBuffer(xdb.IPv4, dbData)
|
|
if err != nil {
|
|
panic(fmt.Errorf("failed to create searcher with content: %s", err))
|
|
}
|
|
|
|
}
|
|
|
|
type IpInfo struct {
|
|
Country string `json:"country"`
|
|
Area string `json:"area"`
|
|
Province string `json:"province"`
|
|
City string `json:"city"`
|
|
Isp string `json:"isp"`
|
|
}
|
|
|
|
func FindE(ipStr string) (info *IpInfo, err error) {
|
|
info = &IpInfo{}
|
|
// 国家|区域|省份|城市|ISP
|
|
res, err := searcher.SearchByStr(ipStr)
|
|
if err != nil {
|
|
return
|
|
}
|
|
//fmt.Println(res)
|
|
|
|
sp := strings.Split(res, "|")
|
|
if len(sp) < 5 {
|
|
return
|
|
}
|
|
|
|
info.Country = convertEmpty(sp[0])
|
|
info.Area = convertEmpty(sp[1])
|
|
info.Province = convertEmpty(sp[2])
|
|
info.City = convertEmpty(sp[3])
|
|
info.Isp = convertEmpty(sp[4])
|
|
|
|
return info, nil
|
|
}
|
|
|
|
func Find(ipStr string) *IpInfo {
|
|
info, _ := FindE(ipStr)
|
|
return info
|
|
}
|
|
|
|
func convertEmpty(s string) string {
|
|
if s == "0" || s == "" {
|
|
return "NULL"
|
|
}
|
|
|
|
return s
|
|
}
|
|
|
|
func (i *IpInfo) ToString() string {
|
|
return i.Country + "-" + i.Province + "-" + i.City + "-" + i.Isp
|
|
}
|