2020-07-21 06:19:52 +08:00
|
|
|
|
package ipip
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"log"
|
|
|
|
|
"os"
|
|
|
|
|
|
|
|
|
|
"github.com/ipipdotnet/ipdb-go"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type IPIPFree struct {
|
|
|
|
|
*ipdb.City
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-09 14:48:28 +08:00
|
|
|
|
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")
|
2022-03-02 12:34:11 +08:00
|
|
|
|
return nil, err
|
2020-07-21 06:19:52 +08:00
|
|
|
|
} else {
|
|
|
|
|
db, err := ipdb.NewCity(filePath)
|
|
|
|
|
if err != nil {
|
2022-03-02 12:34:11 +08:00
|
|
|
|
return nil, err
|
2020-07-21 06:19:52 +08:00
|
|
|
|
}
|
2022-03-02 12:34:11 +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 {
|
2023-05-20 17:14:03 +08:00
|
|
|
|
Country string `json:"country"`
|
|
|
|
|
Region string `json:"region"`
|
|
|
|
|
City string `json:"city"`
|
2021-08-02 12:01:25 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
}
|
2023-05-20 17:53:43 +08:00
|
|
|
|
|
|
|
|
|
func (db IPIPFree) Name() string {
|
|
|
|
|
return "ipip"
|
|
|
|
|
}
|