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

73 lines
1.3 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"
"github.com/spf13/viper"
2020-07-17 09:05:25 +08:00
)
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
}
lang := viper.GetString("selected.lang")
if lang == "" {
lang = "zh-CN"
2021-08-11 10:02:54 +08:00
}
2021-08-02 12:01:25 +08:00
result = Result{
2021-08-11 10:02:54 +08:00
Country: record.Country.Names[lang],
2023-05-20 17:14:03 +08:00
Area: record.City.Names[lang],
2020-07-17 09:05:25 +08:00
}
2021-08-02 12:01:25 +08:00
return
}
func (db GeoIP) Name() string {
return "geoip"
}
2021-08-02 12:01:25 +08:00
type Result struct {
2023-05-20 17:14:03 +08:00
Country string `json:"country"`
Area string `json:"area"`
2021-08-02 12:01:25 +08:00
}
func (r Result) String() string {
2023-05-20 17:14:03 +08:00
if r.Area == "" {
2021-08-02 12:01:25 +08:00
return r.Country
2020-07-17 09:05:25 +08:00
} else {
2023-05-20 17:14:03 +08:00
return fmt.Sprintf("%s %s", r.Country, r.Area)
2020-07-17 09:05:25 +08:00
}
}