当前位置:网站首页>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做了简单的封装.
边栏推荐
- es 读流程源码解析
- golang刷leetcode动态规划(12)最小路径和
- leetcode刷题记录:7.整数反转,8.字符串转整数,9.回文数
- Parse common methods in the Collection interface that are overridden by subclasses
- ECCV 2022 | 通往数据高效的Transformer目标检测器
- 2022-07-26
- 7月29-31 | APACHECON ASIA 2022
- Golang source code analysis: juju/ratelimit
- AI Scientist: Automatically discover hidden state variables of physical systems
- 网络协议介绍
猜你喜欢
解析Collection接口中的常用的被实现子类重写的方法
What is a Field Service Management System (FSM)?what is the benefit?
溜不溜是个问题
解析List接口中的常用的被实现子类重写的方法
Fetch 请求不转换BLOB正常显示GBK编码的数据
牛客题目——滑动窗口的最大值、矩阵最长递增路径、顺时针旋转矩阵、接雨水问题
ShardingSphere-proxy +PostgreSQL实现读写分离(静态策略)
即时通讯开发移动端网络短连接的优化手段
Mysql安装流程 【压缩版】
ShardingSphere-proxy +PostgreSQL implements read-write separation (static strategy)
随机推荐
ABAP语法小复习
4 kmiles join YiSheng group, with more strong ability of digital business, accelerate China's cross-border electricity full domain full growth
PG's SQL execution plan
TPAMI2022 | TransCL: based on the study the compression of the Transformer, more flexible and more powerful
LM小型可编程控制器软件(基于CoDeSys)笔记二十五:plc的数据存储区(数字量输入通道部分)
ShardingSphere-proxy +PostgreSQL implements read-write separation (static strategy)
云平台简介
软考 ----- UML设计与分析(下)
实现fashion_minst服装图像分类
golang刷leetcode 经典(9)为运算表达式设计优先级
ShapeableImageView 的使用,告别shape、三方库
技术分享 | Apache Linkis 快速集成网页IDE工具 Scriptis
力扣每日一题-第46天-344. 反转字符串
Parse common methods in the Collection interface that are overridden by subclasses
SQL 入门之第一讲——MySQL 8.0.29安装教程(windows 64位)
golang源码分析之geoip2-golang
B站HR对面试者声称其核心用户都是生活中的Loser
译出我精彩 | 7月墨力翻译计划获奖名单公布
谷歌竞价机器学习如何去理解?
分享一个 web 应用版本监测 (更新) 的工具库