go ( golang ) 使用 geoip库, 通过ip 获取国家,省市,城市

Golang · Terry · 于 6年前 发布 · 19397 次阅读

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/Shanghai
Coordinates: 30.2936, 120.1614

OK。

本文由 Terry 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。

共收到 0 条回复
没有找到数据。
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics