当前位置:网站首页>Geoip2 - golang golang source code analysis
Geoip2 - golang golang source code analysis
2022-08-02 23:03:00 【User 9710217】
https://github.com/oschwald/geoip2-golang用来解析
[GeoLite2](http://dev.maxmind.com/geoip/geoip2/geolite2/)
and [GeoIP2](http://www.maxmind.com/en/geolocation_landing)Database a kit.类似于nginx的https://github.com/leev/ngx_http_geoip2_module
GeoIP2What's the use of the database?我们可以根据ip来获取ipResponse of regional location and do relevant business:
1,简单的cdn,根据ipGeographic information is redirected to the appropriatecdn服务器
2,Do business fixed area block,比如:Don't give the Japanese customers
3,做国际化,According to the different places for different language services.
For example, we commonly used online toolshttps://github.com/zu1k/nali 其实就用到了geoip2-golang这个包来解析GeoIP2数据.下面,We see this package should be how to use:
package main
import (
"fmt"
"log"
"net"
"github.com/oschwald/geoip2-golang"
)
func main() {
db, err := geoip2.Open("./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("180.101.49.12") //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
}非常简单,加载GeoLite2-City.mmdb数据库,解析ip地址,通过ipAddress loading city information.
接着,我们详细分析下geoip2-golang这个包的源码.Its source code is very simple only a file:
reader.go调用了maxminddbData analysis packagegithub.com/oschwald/maxminddb-golang来做 数据的解析,Just do a layer on the interface encapsulation,And the corresponding geographic data format(企业、城市、国家、AnonymousIP、Domain、ISP)的定义.
比如城市信息:
// The City struct corresponds to the data in the GeoIP2/GeoLite2 City
// databases.
type City struct {
City struct {
GeoNameID uint `maxminddb:"geoname_id"`
Names map[string]string `maxminddb:"names"`
} `maxminddb:"city"`
Continent struct {
Code string `maxminddb:"code"`
GeoNameID uint `maxminddb:"geoname_id"`
Names map[string]string `maxminddb:"names"`
} `maxminddb:"continent"`
Country struct {
GeoNameID uint `maxminddb:"geoname_id"`
IsInEuropeanUnion bool `maxminddb:"is_in_european_union"`
IsoCode string `maxminddb:"iso_code"`
Names map[string]string `maxminddb:"names"`
} `maxminddb:"country"`
Location struct {
AccuracyRadius uint16 `maxminddb:"accuracy_radius"`
Latitude float64 `maxminddb:"latitude"`
Longitude float64 `maxminddb:"longitude"`
MetroCode uint `maxminddb:"metro_code"`
TimeZone string `maxminddb:"time_zone"`
} `maxminddb:"location"`
Postal struct {
Code string `maxminddb:"code"`
} `maxminddb:"postal"`
RegisteredCountry struct {
GeoNameID uint `maxminddb:"geoname_id"`
IsInEuropeanUnion bool `maxminddb:"is_in_european_union"`
IsoCode string `maxminddb:"iso_code"`
Names map[string]string `maxminddb:"names"`
} `maxminddb:"registered_country"`
RepresentedCountry struct {
GeoNameID uint `maxminddb:"geoname_id"`
IsInEuropeanUnion bool `maxminddb:"is_in_european_union"`
IsoCode string `maxminddb:"iso_code"`
Names map[string]string `maxminddb:"names"`
Type string `maxminddb:"type"`
} `maxminddb:"represented_country"`
Subdivisions []struct {
GeoNameID uint `maxminddb:"geoname_id"`
IsoCode string `maxminddb:"iso_code"`
Names map[string]string `maxminddb:"names"`
} `maxminddb:"subdivisions"`
Traits struct {
IsAnonymousProxy bool `maxminddb:"is_anonymous_proxy"`
IsSatelliteProvider bool `maxminddb:"is_satellite_provider"`
} `maxminddb:"traits"`
}先看下open函数
func Open(file string) (*Reader, error) {
reader, err := maxminddb.Open(file)
if err != nil {
return nil, err
}
dbType, err := getDBType(reader)
return &Reader{reader, dbType}, err
}它调用了 maxminddb.Open返回了一个Reader
type Reader struct {
mmdbReader *maxminddb.Reader
databaseType databaseType
}Reader上定义了City,County等函数
func (r *Reader) City(ipAddress net.IP) (*City, error) {
if isCity&r.databaseType == 0 {
return nil, InvalidMethodError{"City", r.Metadata().DatabaseType}
}
var city City
err := r.mmdbReader.Lookup(ipAddress, &city)
return &city, err
}These functions are just formmdbReader.Lookup做了简单的封装.
边栏推荐
猜你喜欢

Redis集群配置

B站HR对面试者声称其核心用户都是生活中的Loser

Axure9的元件用法

Fetch 请求不转换BLOB正常显示GBK编码的数据

2022-07-26

当TIME_WAIT状态的TCP正常挥手,收到SYN后…

顺序查找和折半查找,看这篇就够了

Brain-computer interface 003 | Musk said that he has realized a virtual self-dialogue with the cloud, and related concept shares have risen sharply

ShapeableImageView 的使用,告别shape、三方库

Leetcode刷题——单调栈问题(739每日温度问题、496下一个更大元素I、503下一个更大元素 II)
随机推荐
Axure9的元件用法
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
You want the metagenomics - microbiome knowledge in all the (2022.8)
JWT学习
什么是 IDE
Triacetin是什么化学材料
「面试必会」这应该是最有深度的TCP三次握手、四次挥手细节讲解
The so-called fighting skill again gao also afraid of the chopper - partition, depots, table, and the merits of the distributed
【手撕AHB-APB Bridge】~ AMBA总线 之 APB
Thread线程类基本使用(下)
遇上Mysql亿级优化,怎么办
ShapeableImageView 的使用,告别shape、三方库
【 LeetCode 】 1374. Generate each character string is an odd number
光源控制器接口定义说明
es 读流程源码解析
基于“无依赖绝对定位”实现的圣杯三栏布局
基于 flex 布局实现的三栏布局
姑姑:给小学生出点口算题
Leetcode刷题——单调栈问题(739每日温度问题、496下一个更大元素I、503下一个更大元素 II)
程序员也许都缺一个“二舅”精神