YiTao/util/geoip.go

39 lines
791 B
Go
Raw Normal View History

2024-11-09 14:59:27 +08:00
package util
import (
"net"
"github.com/oschwald/geoip2-golang"
)
var GeoIpDB *geoip2.Reader
func InitGeoIP(path string) (*geoip2.Reader, error) {
db, err := geoip2.Open(path)
if err != nil {
return nil, err
}
GeoIpDB = db
return db, nil
}
func GetCityAndCountry_zh(ip string) (string, string, error) {
record, err := GeoIpDB.City(net.ParseIP(ip))
if err != nil {
return "", "", err
}
return record.City.Names["zh-CN"], record.Country.Names["zh-CN"], nil
}
func GetCityAndCountry_en(ip string) (string, string, error) {
record, err := GeoIpDB.City(net.ParseIP(ip))
if err != nil {
return "", "", err
}
return record.City.Names["en"], record.Country.Names["en"], nil
}
func GetCityAndCountry(ip string) (string, string, error) {
return GetCityAndCountry_en(ip)
}