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"
|
2022-07-21 14:14:08 +08:00
|
|
|
|
"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
|
2022-03-02 12:34:11 +08:00
|
|
|
|
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)
|
2022-03-02 12:34:11 +08:00
|
|
|
|
return nil, err
|
2020-07-17 11:37:03 +08:00
|
|
|
|
} else {
|
|
|
|
|
db, err := geoip2.Open(filePath)
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Fatal(err)
|
|
|
|
|
}
|
2022-03-02 12:34:11 +08:00
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-09 14:59:02 +08:00
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 17:53:43 +08:00
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
}
|