Go --- 一个根据IP查询地址的包geoip2

简介: Go --- 一个根据IP查询地址的包geoip2

IP 地理定位本质上是不精确的。地点通常靠近人口中心。所以如果是用来定位的话,不应该使用IP进行。

简介

这个包是用来解析MaxMind 的GeoLite2GeoIP2 数据库的。这个库是使用Go maxminddb阅读器构建的。数据库记录的所有数据都使用这个库进行解码。

GeoLite2是全球免费的IP地理定位数据库,所以该包的作用是根据IP获取地址、经纬度等详细信息的。

优点:

  • 开源免费
  • 查询速度较快

使用

安装数据库

在使用该包前,我们需要先下载GeoLite2 数据库。

我们使用GeoLite2来演示。

首先先下载GeoLite2,这一步需要注册。

GeoLite2下载地址

当然我们也可以在网上找到GeoLite2数据库Geolite2资源,不需要注册,因为IP是多变的所以使用以前版本的数据库可能会造成数据丢失的问题,建议还是注册一个,毕竟注册后下载是免费的(就是过程有点麻烦)。

GeoLite2免注册下载

下载好后解压出来GeoLite2-City.mmdb文件,把该文件放在项目目录下。

感谢候体宗的博客提供的资源

安装包

go get github.com/oschwald/geoip2-golang

使用代码

package main
import (
   "fmt"
   "github.com/oschwald/geoip2-golang"
   "log"
   "net"
)
func main() {
   // 读取数据库
   db, err := geoip2.Open("./GeoLite2-City.mmdb")
   if err != nil {
      log.Fatal(err)
   }
   defer db.Close()
   // 给定一个ip
   // 如果给定的ip不存在或是空字串,则返回ip为nil
   ip := net.ParseIP("81.2.69.142")
   record, err := db.City(ip)
   if err != nil {
      log.Fatal(err)
   }
   var (
      city      string
      provinces  string
      country    string
      continent  string
      timeZone   string
      latitude   float64
      longitude  float64
   )
   // 城市名称
   if len(record.City.Names) > 0 {
      city = record.City.Names["zh-CN"]
      //fmt.Println(record.City.Names["zh-CN"])
   }
   // 省份
   if len(record.Subdivisions) > 0 {
      if len(record.Subdivisions[0].Names) > 0 {
         provinces = record.Subdivisions[0].Names["zh-CN"]
         //fmt.Println(record.Subdivisions[0].Names["zh-CN"])
      }
   }
   // 国家名
   if len(record.Country.Names) > 0 {
      country = record.Country.Names["zh-CN"]
      //fmt.Println(record.Country.Names["zh-CN"])
   }
   // 洲名
   if len(record.Continent.Names) > 0 {
      continent = record.Continent.Names["zh-CN"]
      //fmt.Println(record.Continent.Names["zh-CN"])
   }
   // 时区
   timeZone = record.Location.TimeZone
   //fmt.Println(record.Location.TimeZone)
   // 纬度
   latitude = record.Location.Latitude
   // 经度
   longitude = record.Location.Longitude
   fmt.Printf("ip所在地为%s-%s-%s-%s,时区为%s,纬度为%f,经度为%f",
      continent, country, provinces, city, timeZone, latitude, longitude)
}

了解更多:

golang-pkg-geoip2

GeoLite2官网文档


相关文章
|
3月前
|
固态存储 测试技术 Go
Go语言 os包 不可不知的性能排行榜
Go语言 os包 不可不知的性能排行榜
55 0
|
3月前
|
Go
高效Go语言编程:os包实用技术大揭示
高效Go语言编程:os包实用技术大揭示
40 0
|
3月前
|
安全 Go
时间旅行者的工具箱:Go语言time包解读
时间旅行者的工具箱:Go语言time包解读
35 0
|
3月前
|
关系型数据库 MySQL Go
工厂模式+自动注册管理Go多包结构体
工厂模式+自动注册管理Go多包结构体
43 1
|
4月前
|
中间件 Go 开发者
Go net http包
Go net http包
38 0
|
4月前
|
Go
Go string bytes、strings、strconv和unicode包相关方法
Go string bytes、strings、strconv和unicode包相关方法
26 0
|
4月前
|
Go
go fmt包格式化
go fmt包格式化
30 0
|
2月前
|
Go C语言
安装go-sqlite3包时报exec: "gcc": executable file not found in %PATH%解决办法
安装go-sqlite3包时报exec: "gcc": executable file not found in %PATH%解决办法
|
3月前
|
Go
Go命令行解析神器入门 - 10分钟上手flag包
Go命令行解析神器入门 - 10分钟上手flag包
39 0
|
3月前
|
Go 索引
Go系统编程不求人:os包全面解析
Go系统编程不求人:os包全面解析
70 0