-
Notifications
You must be signed in to change notification settings - Fork 5
/
geolocate.go
66 lines (59 loc) · 1.36 KB
/
geolocate.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 geolocate
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// Geolocate returns a rough location based on your IP
func (g *GoogleGeo) Geolocate() (*Point, error) {
data, err := g.geolocateRequest()
if err != nil {
return nil, err
}
res := &geolocateResponse{}
json.Unmarshal(data, res)
if res.Error.Code != 0 {
e := res.Error.Errors[0]
return nil, fmt.Errorf(e.Domain + "." + e.Reason + "." + e.Message)
}
return &Point{Lat: res.Location.Lat, Lng: res.Location.Lng}, nil
}
// This struct contains selected fields from Google's Geocoding Service response
type geolocateResponse struct {
Error struct {
Code int
Message string
Errors []struct {
Domain string
Reason string
Message string
}
}
Location struct {
Lat float64
Lng float64
}
}
func (g *GoogleGeo) geolocateRequest() ([]byte, error) {
if g.apiKey == "" {
return nil, fmt.Errorf("Google API key not provided")
}
dst := "https://www.googleapis.com/geolocation/v1/geolocate?key=" + g.apiKey
form := url.Values{}
req, err := http.NewRequest("POST", dst, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
resp, requestErr := g.client.Do(req)
if requestErr != nil {
return nil, requestErr
}
data, dataReadErr := ioutil.ReadAll(resp.Body)
if dataReadErr != nil {
return nil, dataReadErr
}
return data, nil
}