-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
89 lines (72 loc) · 1.95 KB
/
ip.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
package main
import (
"net"
"github.com/oschwald/geoip2-golang"
)
type geoParser struct {
geoASN *geoip2.Reader
geoCity *geoip2.Reader
// geoCountry *geoip2.Reader
}
type geonameData struct {
valid bool
id uint
city string
country string
administratorArea string
}
type geoResult struct {
GeoIP string `json:"IP"`
GeoValid bool `json:"IsValid"`
GeoIPAutonomousSystemNumber uint `json:"AutonomousSystemNumber"`
GeoIPAutonomousSystemOrganization string `json:"AutonomousSystemOrganization"`
GeoIPCity string `json:"City"`
GeoIPCityGeoNameID uint `json:"CityGeoNameID"`
GeoIPCountry string `json:"Country"`
GeoIPLocationLatitude float64 `json:"LocationLatitude"`
GeoIPLocationLongitude float64 `json:"LocationLongitude"`
}
func newGeoParser(
mmdbCityPath string,
mmdbASNPath string,
) (*geoParser, error) {
dbCity, err := geoip2.Open(mmdbCityPath)
if err != nil {
return nil, err
}
dbASN, err := geoip2.Open(mmdbASNPath)
if err != nil {
return nil, err
}
geoIPParser := geoParser{
geoASN: dbASN,
geoCity: dbCity,
}
return &geoIPParser, nil
}
func (geoParser *geoParser) newResultFromIP(ipString string) geoResult {
obj := geoResult{
GeoValid: false,
}
ip := net.ParseIP(ipString)
if ip == nil {
return obj
}
obj.GeoIP = ip.String()
recordCity, err := geoParser.geoCity.City(ip)
if err == nil {
obj.GeoValid = true
obj.GeoIPCity = recordCity.City.Names["en"]
obj.GeoIPCityGeoNameID = recordCity.City.GeoNameID
obj.GeoIPCountry = recordCity.Country.IsoCode
obj.GeoIPLocationLatitude = recordCity.Location.Latitude
obj.GeoIPLocationLongitude = recordCity.Location.Longitude
}
recordASN, err := geoParser.geoASN.ASN(ip)
if err == nil {
obj.GeoValid = true
obj.GeoIPAutonomousSystemOrganization = recordASN.AutonomousSystemOrganization
obj.GeoIPAutonomousSystemNumber = recordASN.AutonomousSystemNumber
}
return obj
}