This repository has been archived by the owner on Sep 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geolocation.go
82 lines (68 loc) · 1.89 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package store
import (
"encoding/xml"
"fmt"
"net/http"
"github.com/lnkk-ai/url-shortener/internal/types"
"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
}
// AsInternal converts the geolocation into the internal DS struct
func (r *LocationType) AsInternal() *types.GeoLocationDS {
location := types.GeoLocationDS{
IP: r.IP,
Host: r.Host,
ISP: r.Isp,
City: r.City,
CountryCode: r.Countrycode,
CountryName: r.Countryname,
Latitude: r.Latitude,
Longitude: r.Longitude,
}
return &location
}