1
0
mirror of https://github.com/zu1k/nali.git synced 2025-01-22 21:29:02 +08:00
nali/pkg/geoip/geoip.go

49 lines
867 B
Go
Raw Normal View History

2020-07-17 09:05:25 +08:00
package geoip
import (
"fmt"
"log"
"net"
2020-07-17 11:37:03 +08:00
"os"
2020-07-17 09:05:25 +08:00
"github.com/oschwald/geoip2-golang"
)
2020-07-17 09:50:06 +08:00
// GeoIP2
2020-07-17 09:05:25 +08:00
type GeoIP struct {
db *geoip2.Reader
}
2020-07-17 09:50:06 +08:00
// new geoip from db file
2020-07-17 11:37:03 +08:00
func NewGeoIP(filePath string) (geoip GeoIP) {
// 判断文件是否存在
_, err := os.Stat(filePath)
if err != nil && os.IsNotExist(err) {
log.Println("文件不存在,请自行下载 Geoip2 City库并保存在", filePath)
os.Exit(1)
} else {
db, err := geoip2.Open(filePath)
if err != nil {
log.Fatal(err)
}
geoip = GeoIP{db: db}
2020-07-17 09:05:25 +08:00
}
2020-07-17 11:37:03 +08:00
return
2020-07-17 09:05:25 +08:00
}
2020-07-17 09:50:06 +08:00
// find ip info
2020-07-17 09:05:25 +08:00
func (g GeoIP) Find(ip string) string {
ipData := net.ParseIP(ip)
record, err := g.db.City(ipData)
if err != nil {
log.Fatal(err)
}
country := record.Country.Names["zh-CN"]
city := record.City.Names["zh-CN"]
if city == "" {
return country
} else {
return fmt.Sprintf("%s %s", country, city)
}
}