-
Notifications
You must be signed in to change notification settings - Fork 0
/
postal.go
79 lines (71 loc) · 1.94 KB
/
postal.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
package geonames
import (
"context"
"fmt"
"net/url"
)
type postalResponse struct {
PostalCodes []struct {
AdminCode1 string `json:"adminCode1"`
Lng float64 `json:"lng"`
CountryCode string `json:"countryCode"`
PostalCode string `json:"postalCode"`
AdminName1 string `json:"adminName1"`
ISO31662 string `json:"ISO3166-2"`
PlaceName string `json:"placeName"`
Lat float64 `json:"lat"`
} `json:"postalCodes"`
}
type PostalCode struct {
PlaceName string
AdminName1 string
Position Position
CountryCode string
PostalCode string
AdminCode1 string
}
// GetPostalCode retrieves postal codes for the given place name and the country code.
func (c Client) GetPostCode(ctx context.Context, place, country string) ([]PostalCode, error) {
url, err := c.buildPostalURL(place, country)
if err != nil {
return nil, err
}
var pr postalResponse
if err := c.get(ctx, url, &pr); err != nil {
return nil, err
}
var postalCodes []PostalCode
for _, pc := range pr.PostalCodes {
p := PostalCode{
PlaceName: pc.PlaceName,
AdminName1: pc.AdminName1,
Position: Position{
Lat: pc.Lat,
Lng: pc.Lng,
},
PostalCode: pc.PostalCode,
CountryCode: pc.CountryCode,
AdminCode1: pc.AdminCode1,
}
postalCodes = append(postalCodes, p)
}
return postalCodes, nil
}
func (c Client) buildPostalURL(placeName, countryCode string) (string, error) {
params := url.Values{
"placename": {placeName},
"country": {countryCode},
"username": {c.UserName},
}
basePostal := fmt.Sprintf("%s/postalCodeSearchJSON", c.BaseURL)
u, err := url.Parse(basePostal)
if err != nil {
return "", fmt.Errorf("parsing base url for postal, %w", err)
}
u.RawQuery = params.Encode()
return u.String(), nil
}
// GetPostalCode takes place and country and returns postal codes.
func GetPostCode(place, country string) ([]PostalCode, error) {
return ClientFromEnv.GetPostCode(context.Background(), place, country)
}