1
0
mirror of https://github.com/zu1k/nali.git synced 2025-01-23 05:39:03 +08:00
nali/pkg/ipip/ipip.go

57 lines
1.1 KiB
Go
Raw Normal View History

2020-07-21 06:19:52 +08:00
package ipip
import (
"fmt"
"log"
"os"
"github.com/ipipdotnet/ipdb-go"
)
type IPIPFree struct {
*ipdb.City
}
func NewIPIP(filePath string) (*IPIPFree, error) {
2020-07-21 06:19:52 +08:00
_, err := os.Stat(filePath)
if err != nil && os.IsNotExist(err) {
log.Printf("IPIP数据库不存在请手动下载解压后保存到本地: %s \n", filePath)
log.Println("下载链接: https://www.ipip.net/product/ip.html")
return nil, err
2020-07-21 06:19:52 +08:00
} else {
db, err := ipdb.NewCity(filePath)
if err != nil {
return nil, err
2020-07-21 06:19:52 +08:00
}
return &IPIPFree{City: db}, nil
2020-07-21 06:19:52 +08:00
}
}
2021-08-02 12:01:25 +08:00
type Result struct {
Country string
Region string
City string
}
func (r Result) String() string {
if r.City == "" {
return fmt.Sprintf("%s %s", r.Country, r.Region)
}
return fmt.Sprintf("%s %s %s", r.Country, r.Region, r.City)
}
func (db IPIPFree) Find(query string, params ...string) (result fmt.Stringer, err error) {
info, err := db.FindInfo(query, "CN")
if err != nil || info == nil {
return nil, err
2020-07-21 06:19:52 +08:00
} else {
2021-08-02 12:01:25 +08:00
// info contains more info
result = Result{
Country: info.CountryName,
Region: info.RegionName,
City: info.CityName,
2020-07-21 06:19:52 +08:00
}
2021-08-02 12:01:25 +08:00
return
2020-07-21 06:19:52 +08:00
}
}