-
Notifications
You must be signed in to change notification settings - Fork 69
/
http_geocoder.go
156 lines (129 loc) · 3.24 KB
/
http_geocoder.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package geo
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// DefaultTimeout for the request execution
const DefaultTimeout = time.Second * 8
// ErrTimeout occurs when no response returned within timeoutInSeconds
var ErrTimeout = errors.New("TIMEOUT")
// EndpointBuilder defines functions that build urls for geocode/reverse geocode
type EndpointBuilder interface {
GeocodeURL(string) string
ReverseGeocodeURL(Location) string
}
// ResponseParserFactory creates a new ResponseParser
type ResponseParserFactory func() ResponseParser
// ResponseParser defines functions that parse response of geocode/reverse geocode
type ResponseParser interface {
Location() (*Location, error)
Address() (*Address, error)
}
// HTTPGeocoder has EndpointBuilder and ResponseParser
type HTTPGeocoder struct {
EndpointBuilder
ResponseParserFactory
}
func (g HTTPGeocoder) GeocodeWithContext(ctx context.Context, address string) (*Location, error) {
responseParser := g.ResponseParserFactory()
type geoResp struct {
l *Location
e error
}
ch := make(chan geoResp, 1)
go func(ch chan geoResp) {
if err := response(ctx, g.GeocodeURL(url.QueryEscape(address)), responseParser); err != nil {
ch <- geoResp{
l: nil,
e: err,
}
}
loc, err := responseParser.Location()
ch <- geoResp{
l: loc,
e: err,
}
}(ch)
select {
case <-ctx.Done():
return nil, ErrTimeout
case res := <-ch:
return res.l, res.e
}
}
// Geocode returns location for address
func (g HTTPGeocoder) Geocode(address string) (*Location, error) {
ctx, cancel := context.WithTimeout(context.TODO(), DefaultTimeout)
defer cancel()
return g.GeocodeWithContext(ctx, address)
}
// ReverseGeocode returns address for location
func (g HTTPGeocoder) ReverseGeocode(lat, lng float64) (*Address, error) {
responseParser := g.ResponseParserFactory()
ctx, cancel := context.WithTimeout(context.TODO(), DefaultTimeout)
defer cancel()
type revResp struct {
a *Address
e error
}
ch := make(chan revResp, 1)
go func(ch chan revResp) {
if err := response(ctx, g.ReverseGeocodeURL(Location{lat, lng}), responseParser); err != nil {
ch <- revResp{
a: nil,
e: err,
}
}
addr, err := responseParser.Address()
ch <- revResp{
a: addr,
e: err,
}
}(ch)
select {
case <-ctx.Done():
return nil, ErrTimeout
case res := <-ch:
return res.a, res.e
}
}
// Response gets response from url
func response(ctx context.Context, url string, obj ResponseParser) error {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
req.Header.Add("User-Agent", "geo-golang/1.0")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
body := strings.Trim(string(data), " []")
DebugLogger.Printf("Received response: %s\n", body)
if body == "" {
return nil
}
if err := json.Unmarshal([]byte(body), obj); err != nil {
ErrLogger.Printf("Error unmarshalling response: %s\n", err.Error())
return err
}
return nil
}
// ParseFloat is a helper to parse a string to a float
func ParseFloat(value string) float64 {
f, _ := strconv.ParseFloat(value, 64)
return f
}