1 | package location |
||
2 | |||
3 | import ( |
||
4 | "encoding/json" |
||
5 | "errors" |
||
6 | "fmt" |
||
7 | "net/http" |
||
8 | ) |
||
9 | |||
10 | // LocationResultData : location struct |
||
11 | type LocationResultData struct { |
||
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
12 | ResultCount int `json:"totalResultsCount"` |
||
13 | Geonames []Geoname `json:"geonames"` |
||
14 | } |
||
15 | |||
16 | // Geoname : location geonames struct |
||
17 | type Geoname struct { |
||
18 | GeonameID int `json:"geonameId"` |
||
19 | CountryID string `json:"countryId"` |
||
20 | ToponymName string `json:"toponymName"` |
||
21 | Population int `json:"population"` |
||
22 | CountryCode string `json:"countryCode"` |
||
23 | Name string `json:"name"` |
||
24 | CountryName string `json:"countryName"` |
||
25 | Lat string `json:"lat"` |
||
26 | Lng string `json:"lng"` |
||
27 | } |
||
28 | |||
29 | // GetCoordinates returns latitude and longitude |
||
30 | func (l LocationResultData) GetCoordinates() (string, string) { |
||
31 | return l.Geonames[0].Lat, l.Geonames[0].Lng |
||
32 | } |
||
33 | |||
34 | // New creates and returns location struct |
||
35 | func New(user string, locationName string) (result LocationResultData, err error) { |
||
36 | resp, err := http.Get(fmt.Sprintf("http://api.geonames.org/searchJSON?q=%v&maxRows=1&username=%v", locationName, user)) |
||
37 | if err != nil { |
||
38 | return result, err |
||
39 | } |
||
40 | |||
41 | err = json.NewDecoder(resp.Body).Decode(&result) |
||
42 | if err != nil { |
||
43 | return result, err |
||
44 | } |
||
45 | |||
46 | if len(result.Geonames) == 0 { |
||
47 | return result, errors.New("City not found") |
||
48 | } |
||
49 | |||
50 | return result, nil |
||
51 | } |
||
52 |