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

70 lines
1.2 KiB
Go
Raw Normal View History

2020-07-17 09:05:25 +08:00
package geoip
import (
2021-08-02 12:01:25 +08:00
"errors"
2020-07-17 09:05:25 +08:00
"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
}
2021-08-02 12:01:25 +08:00
// new geoip from database file
func NewGeoIP(filePath string) (*GeoIP, error) {
2020-07-17 11:37:03 +08:00
// 判断文件是否存在
_, err := os.Stat(filePath)
if err != nil && os.IsNotExist(err) {
log.Println("文件不存在,请自行下载 Geoip2 City库并保存在", filePath)
return nil, err
2020-07-17 11:37:03 +08:00
} else {
db, err := geoip2.Open(filePath)
if err != nil {
log.Fatal(err)
}
return &GeoIP{db: db}, nil
2020-07-17 09:05:25 +08:00
}
}
2021-08-02 12:01:25 +08:00
func (g GeoIP) Find(query string, params ...string) (result fmt.Stringer, err error) {
ip := net.ParseIP(query)
if ip == nil {
return nil, errors.New("Query should be valid IP")
}
record, err := g.db.City(ip)
2020-07-17 09:05:25 +08:00
if err != nil {
2021-08-02 12:01:25 +08:00
return
}
2021-08-11 10:02:54 +08:00
lang := "zh-CN"
if len(params) > 0 {
if _, ok := record.Country.Names[params[0]]; ok {
lang = params[0]
}
}
2021-08-02 12:01:25 +08:00
result = Result{
2021-08-11 10:02:54 +08:00
Country: record.Country.Names[lang],
City: record.City.Names[lang],
2020-07-17 09:05:25 +08:00
}
2021-08-02 12:01:25 +08:00
return
}
type Result struct {
Country string
City string
}
func (r Result) String() string {
if r.City == "" {
return r.Country
2020-07-17 09:05:25 +08:00
} else {
2021-08-02 12:01:25 +08:00
return fmt.Sprintf("%s %s", r.Country, r.City)
2020-07-17 09:05:25 +08:00
}
}