-
Notifications
You must be signed in to change notification settings - Fork 7
/
search.go
51 lines (46 loc) · 1.2 KB
/
search.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
// Package geonames implements geonames.org APIs.
package geonames
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
)
// ErrNotFound is returned when no result is found.
var ErrNotFound = errors.New("not found")
// A Location represents a geo location with a few properties.
type Location struct {
Name string `json:"name"`
Country string `json:"countryName"`
Latitude string `json:"lat"`
Longitude string `json:"lng"`
}
type searchResponse struct {
Geonames []Location `json:"geonames"`
}
// Search searches a geo name query.
func Search(username string, q string) (*Location, error) {
v := url.Values{}
v.Set("q", q)
v.Set("maxRows", "1")
v.Set("type", "json")
v.Set("username", username)
dest := fmt.Sprintf("http://api.geonames.org/search?%s", v.Encode())
resp, err := http.DefaultClient.Get(dest)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status %v", resp.Status)
}
var r searchResponse
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
return nil, err
}
if len(r.Geonames) == 0 {
return nil, ErrNotFound
}
return &r.Geonames[0], nil
}