tkcashgame_v4/pkg/geo/client.go

61 lines
1.3 KiB
Go

package geo
import (
"log"
"net"
"github.com/oschwald/maxminddb-golang"
)
type GeoClient struct {
Reader *maxminddb.Reader
}
func NewGeoClient(file string) *GeoClient {
db, err := maxminddb.Open(file)
if err != nil {
log.Fatalf("geoip file not found")
}
return &GeoClient{
Reader: db,
}
}
// GeoInfo 地理信息
type GeoInfo struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
Names map[string]string
GeonameID int `maxminddb:"geoname_id"`
} `maxminddb:"country"`
City struct {
Names map[string]string `maxminddb:"names"`
GeonameID int `maxminddb:"geoname_id"`
} `maxminddb:"city"`
Continent struct {
Names map[string]string `maxminddb:"names"`
} `maxminddb:"continent"`
Location struct {
Latitude float64 `maxminddb:"latitude"`
Longitude float64 `maxminddb:"longitude"`
} `maxminddb:"location"`
Postal struct {
Code string `maxminddb:"code"`
} `maxminddb:"postal"`
Subdivisions []struct {
ISOCode string `maxminddb:"iso_code"`
Names map[string]string `maxminddb:"names"`
} `maxminddb:"subdivisions"`
}
// 解析IP地址
func (c *GeoClient) Parse(ip string) (*GeoInfo, error) {
var info GeoInfo
netIp := net.ParseIP(ip)
err := c.Reader.Lookup(netIp, &info)
if err != nil {
return nil, err
}
return &info, nil
}