Initial commit
This commit is contained in:
92
geo/geo.go
Normal file
92
geo/geo.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package geo
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
iplib "github.com/oschwald/geoip2-golang"
|
||||
)
|
||||
|
||||
var db *iplib.Reader
|
||||
|
||||
func Init(file string) (err error) {
|
||||
db, err = iplib.Open(file)
|
||||
return
|
||||
}
|
||||
|
||||
func Close() {
|
||||
if db != nil {
|
||||
db.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func City(ip string) (*iplib.City, error) {
|
||||
return db.City(net.ParseIP(ip))
|
||||
}
|
||||
|
||||
func GetCity(ip string) (string, error) {
|
||||
r, err := db.City(net.ParseIP(ip))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return r.City.Names["en"], nil
|
||||
}
|
||||
|
||||
func GetCountry(ip string) (string, error) {
|
||||
r, err := db.City(net.ParseIP(ip))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return r.Country.Names["en"], nil
|
||||
}
|
||||
|
||||
func GetProvince(ip string) (string, error) {
|
||||
defer func() { recover() }()
|
||||
r, err := db.City(net.ParseIP(ip))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return r.Subdivisions[0].Names["en"], nil
|
||||
}
|
||||
|
||||
//同时获取国家,省份,简写, 城市名称
|
||||
func GetLoc(ip string) (string, string, string, error) {
|
||||
defer func() { recover() }()
|
||||
r, err := db.City(net.ParseIP(ip))
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
|
||||
return r.Country.IsoCode, r.Subdivisions[0].IsoCode, r.City.Names["en"], nil
|
||||
}
|
||||
|
||||
// 获取 iso_code, name
|
||||
func GetContinent(ip string) (string, string, error) {
|
||||
defer func() { recover() }()
|
||||
r, err := db.City(net.ParseIP(ip))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
return r.Continent.Code, r.Continent.Names["en"], nil
|
||||
}
|
||||
|
||||
// Return latitude and longitude
|
||||
func GetCoordinate(ip string) (float64, float64, error) {
|
||||
defer func() { recover() }()
|
||||
r, err := db.City(net.ParseIP(ip))
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
return r.Location.Latitude, r.Location.Longitude, nil
|
||||
}
|
||||
|
||||
func GetTimezone(ip string) (string, error) {
|
||||
defer func() { recover() }()
|
||||
r, err := db.City(net.ParseIP(ip))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return r.Location.TimeZone, nil
|
||||
}
|
||||
Reference in New Issue
Block a user