/
geolocation.go
66 lines (53 loc) · 1.46 KB
/
geolocation.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
package shortener
import (
"encoding/xml"
"fmt"
"net/http"
"golang.org/x/net/html/charset"
)
type (
// LookupResult is the struct returned by a lookup on geoiplookup.net
LookupResult struct {
XMLName xml.Name `xml:"ip"`
Text string `xml:",chardata"`
Results ResultsType `xml:"results"`
}
// ResultsType container for the location
ResultsType struct {
XMLName xml.Name `xml:"results"`
Text string `xml:",chardata"`
Result LocationType `xml:"result"`
}
// LocationType holds the geo data
LocationType struct {
Text string `xml:",chardata"`
IP string `xml:"ip"`
Host string `xml:"host"`
Isp string `xml:"isp"`
City string `xml:"city"`
Countrycode string `xml:"countrycode"`
Countryname string `xml:"countryname"`
Latitude string `xml:"latitude"`
Longitude string `xml:"longitude"`
}
)
// lookupGeoLocation looks up the IP's geolocation
func lookupGeoLocation(ip string) (*LocationType, error) {
url := fmt.Sprintf("http://api.geoiplookup.net/?query=%s", ip)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Status error: %v", resp.StatusCode)
}
var location LookupResult
decoder := xml.NewDecoder(resp.Body)
decoder.CharsetReader = charset.NewReaderLabel
err = decoder.Decode(&location)
if err != nil {
return nil, err
}
return &location.Results.Result, nil
}