Github: https://github.com/oschwald/geoip2-golang
1.进入后,开头部分会告诉下载ip库,打开页面
https://dev.maxmind.com/geoip/geoip2/geolite2/
找到下载地址
也就是下载地址:http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
下载完成后解压,我的地址为:/www/test/ip/GeoLite2-City_20180327/GeoLite2-City.mmdb
2.下载(按照readme步骤)
go get github.com/oschwald/geoip2-golang
安装的过程报错:
package golang.org/x/sys/unix: unrecognized import path "golang.org/x/sys/unix" (https fetch: Get https://golang.org/x/sys/unix?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
被长城墙了,您可以这这么操作:(参看 http://www.fecshop.com/topic/805)
cd ~/go/src mkdir -p golang.org/x cd golang.org/x git clone https://github.com/golang/sys.git
下载完成后,重新安装
go get github.com/oschwald/geoip2-golang
即可完成。
完成后,在main包里面新建ip.go
package main import ( "fmt" "github.com/oschwald/geoip2-golang" "log" "net") func main() { db, err := geoip2.Open("/www/test/ip/GeoLite2-City_20180327/GeoLite2-City.mmdb") if err != nil { log.Fatal(err) } defer db.Close() // If you are using strings that may be invalid, check that ip is not nil ip := net.ParseIP("120.24.37.249") record, err := db.City(ip) if err != nil { log.Fatal(err) } fmt.Printf("Portuguese (BR) city name: %v\n", record.City.Names["zh-CN"]) fmt.Printf("English subdivision name: %v\n", record.Subdivisions[0].Names["en"]) fmt.Printf("Russian country name: %v\n", record.Country.Names["en"]) fmt.Printf("ISO country code: %v\n", record.Country.IsoCode) fmt.Printf("Time zone: %v\n", record.Location.TimeZone) fmt.Printf("Coordinates: %v, %v\n", record.Location.Latitude, record.Location.Longitude) // Output: // Portuguese (BR) city name: Londres // English subdivision name: England // Russian country name: Великобритания // ISO country code: GB // Time zone: Europe/London // Coordinates: 51.5142, -0.0931 }
db, err := geoip2.Open("/www/test/ip/GeoLite2-City_20180327/GeoLite2-City.mmdb")
参数就是上面第一部下载的ip数据库的路径
执行 go run ip.go
, 结果为:
Portuguese (BR) city name: 杭州 English subdivision name: Zhejiang Russian country name: China ISO country code: CN Time zone: Asia/ShanghaiCoordinates: 30.2936, 120.1614
OK。
《本文》有 0 条评论