-
Notifications
You must be signed in to change notification settings - Fork 4
/
geolocator.go
102 lines (78 loc) · 1.9 KB
/
geolocator.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
package main
import (
"encoding/json"
"net/http"
)
const (
mainGeolocatorURL = "http://ip-api.com/json/"
backupGeolocatorURL = "http://api.ipstack.com/"
)
// Geolocator defines the interface for an ip geolocator provider
type Geolocator interface {
Geolocate(ip string) (string, error)
}
type geolocationProvider struct {
Geolocators []Geolocator
}
// NewGeolocationProvider represents a geolocator aggregator
func NewGeolocationProvider(geos ...Geolocator) Geolocator {
return geolocationProvider{Geolocators: geos}
}
func (g geolocationProvider) Geolocate(ip string) (string, error) {
var country string
var err error
for _, locator := range g.Geolocators {
country, err = locator.Geolocate(ip)
if err == nil && ip != "" {
return country, nil
}
}
return country, err
}
type geolocateOption struct {
Locator Geolocator
}
func (g geolocateOption) Apply(e FailedConnEvent) (FailedConnEvent, error) {
country, err := g.Locator.Geolocate(e.IPAddress.String())
if err != nil {
return e, err
}
e.Country = country
return e, nil
}
type ipAPI struct{}
type apiStack struct {
AccessKey string
}
type ipAPIResponse struct {
Country string `json:"country"`
}
func (c ipAPI) Geolocate(ip string) (string, error) {
resp, err := http.Get(mainGeolocatorURL + ip)
if err != nil {
return "", err
}
defer resp.Body.Close()
response := ipAPIResponse{}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return "", err
}
return response.Country, nil
}
type apiStackResponse struct {
CountryName string `json:"country_name"`
}
func (c apiStack) Geolocate(ip string) (string, error) {
resp, err := http.Get(backupGeolocatorURL + ip + "?access_key=" + c.AccessKey)
if err != nil {
return "", err
}
defer resp.Body.Close()
response := apiStackResponse{}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return "", err
}
return response.CountryName, nil
}