/
maxmind.go
108 lines (90 loc) · 2.45 KB
/
maxmind.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package utils
import (
"net"
"strings"
"github.com/oschwald/maxminddb-golang"
)
type MMDBResult struct {
IP string
Reverse string
Via string
ASN int `maxminddb:"autonomous_system_number"`
ASNOrg string `maxminddb:"autonomous_system_organization"`
City struct {
GeoNameID int `maxminddb:"geoname_id"`
Names struct {
EN string `maxminddb:"en"`
JA string `maxminddb:"ja"`
ZH string `maxminddb:"zh-CN"`
} `maxminddb:"names"`
} `maxminddb:"city"`
Continent struct {
Code string `maxminddb:"code"`
GeoNameID int `maxminddb:"geoname_id"`
Names struct {
EN string `maxminddb:"en"`
JA string `maxminddb:"ja"`
ZH string `maxminddb:"zh-CN"`
} `maxminddb:"names"`
} `maxminddb:"continent"`
Country struct {
ISOCode string `maxminddb:"iso_code"`
GeoNameID int `maxminddb:"geoname_id"`
Names struct {
EN string `maxminddb:"en"`
JA string `maxminddb:"ja"`
ZH string `maxminddb:"zh-CN"`
} `maxminddb:"names"`
} `maxminddb:"country"`
RegisteredCountry struct {
ISOCode string `maxminddb:"iso_code"`
GeoNameID int `maxminddb:"geoname_id"`
Names struct {
EN string `maxminddb:"en"`
JA string `maxminddb:"ja"`
ZH string `maxminddb:"zh-CN"`
} `maxminddb:"names"`
} `maxminddb:"registered_country"`
Location struct {
Accuracy int `maxminddb:"accuracy_radius"`
Latitude float32 `maxminddb:"latitude"`
Longitude float32 `maxminddb:"longitude"`
TimeZone string `maxminddb:"time_zone"`
} `maxminddb:"location"`
}
var MaxMindDBs []*maxminddb.Reader
func LoadMaxMindDB(pathList string) error {
if pathList == "" {
return nil
}
MaxMindDBs = []*maxminddb.Reader{}
for _, path := range strings.Split(pathList, ",") {
DWarnf("Maxmind Database | Loading maxmind database, path=%v", path)
mmdb, err := maxminddb.Open(path)
if err != nil {
return DErrorf("Maxmind Database | Cannot load maxmind database, err=%v", err.Error()).Error()
}
MaxMindDBs = append(MaxMindDBs, mmdb)
}
return nil
}
func QueryMaxMindDB(rawIp string) *MMDBResult {
if len(MaxMindDBs) == 0 {
return nil
}
result := MMDBResult{
IP: rawIp,
}
ip := net.ParseIP(rawIp)
if ip == nil {
DErrorf("Maxmind Database | Cannot parse ip address, ip=%v", rawIp)
return &result
}
for _, db := range MaxMindDBs {
err := db.Lookup(ip, &result)
if err != nil {
DErrorf("Maxmind Database | Cannot query mmdb table, ip=%v err=%v", rawIp, err.Error())
}
}
return &result
}