安装依赖:
go get github.com/oschwald/geoip2-golang
数据库文件下载地址(需注册用户):
https://www.maxmind.com/en/accounts/current/geoip/downloads
示例代码:
type Result struct {
Country string `json:"country"`
Province string `json:"province"`
City string `json:"city"`
District string `json:"district"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
func ip2Geo(ip string) (res *Result, err error) {
db, err := geoip2.Open("GeoLite2-City.mmdb")
if err != nil {
return nil, err
}
defer db.Close()
// If you are using strings that may be invalid, check that ip is not nil
ipParse := net.ParseIP(ip)
record, err := db.City(ipParse)
if err != nil {
return nil, err
}
if record.City.Names["zh-CN"] != "" {
res = &Result{
Country: record.Country.Names["zh-CN"],
Province: record.Subdivisions[0].Names["zh-CN"],
City: record.City.Names["zh-CN"],
District: "",
Lat: record.Location.Latitude,
Lon: record.Location.Longitude,
}
}
return res, nil
}
func main() {
res, _ := ip2Geo("39.144.179.123")
fmt.Println(res == nil)
r, _ := json.Marshal(res)
fmt.Println(string(r))
}
type Result struct {
Country string `json:"country"`
Province string `json:"province"`
City string `json:"city"`
District string `json:"district"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
func ip2Geo(ip string) (res *Result, err error) {
db, err := geoip2.Open("GeoLite2-City.mmdb")
if err != nil {
return nil, err
}
defer db.Close()
// If you are using strings that may be invalid, check that ip is not nil
ipParse := net.ParseIP(ip)
record, err := db.City(ipParse)
if err != nil {
return nil, err
}
if record.City.Names["zh-CN"] != "" {
res = &Result{
Country: record.Country.Names["zh-CN"],
Province: record.Subdivisions[0].Names["zh-CN"],
City: record.City.Names["zh-CN"],
District: "",
Lat: record.Location.Latitude,
Lon: record.Location.Longitude,
}
}
return res, nil
}
func main() {
res, _ := ip2Geo("39.144.179.123")
fmt.Println(res == nil)
r, _ := json.Marshal(res)
fmt.Println(string(r))
}
type Result struct { Country string `json:"country"` Province string `json:"province"` City string `json:"city"` District string `json:"district"` Lat float64 `json:"lat"` Lon float64 `json:"lon"` } func ip2Geo(ip string) (res *Result, err error) { db, err := geoip2.Open("GeoLite2-City.mmdb") if err != nil { return nil, err } defer db.Close() // If you are using strings that may be invalid, check that ip is not nil ipParse := net.ParseIP(ip) record, err := db.City(ipParse) if err != nil { return nil, err } if record.City.Names["zh-CN"] != "" { res = &Result{ Country: record.Country.Names["zh-CN"], Province: record.Subdivisions[0].Names["zh-CN"], City: record.City.Names["zh-CN"], District: "", Lat: record.Location.Latitude, Lon: record.Location.Longitude, } } return res, nil } func main() { res, _ := ip2Geo("39.144.179.123") fmt.Println(res == nil) r, _ := json.Marshal(res) fmt.Println(string(r)) }
注意:国外的数据,注意下敏感区域的处理。
自动更新数据的方法
点击获取永久链接
将永久链接复制出来,然后去生成许可证,生成方法如下:
根据提示生成即可,替换永久链接中的 YOUR_LICENSE_KEY 。注意首次生成需要等待几分钟才能生效。