-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgosrm.go
92 lines (74 loc) · 2.06 KB
/
gosrm.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
package gosrm
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strings"
)
type (
// HTTPClient is the interface that can be used to do HTTP calls.
HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// OSRMClient is the base type with helper methods to call OSRM APIs.
// It only holds the base OSRM URL.
OSRMClient struct {
baseURL *url.URL
client HTTPClient
}
// Request is the OSRM's request structure.
// It can be used with all services except tile service.
// Note that for nearest request you have to pass only a coordinate.
Request struct {
// Profile is the profile of the request.
Profile Profile
// Coordinates is the coordinate of the request.
Coordinates []Coordinate
}
)
// New returns a new OSRM client.
func New(baseURL string) (OSRMClient, error) {
var client OSRMClient
u, err := url.Parse(baseURL)
if err != nil {
return client, err
}
client.baseURL = u
client.SetHTTPClient(NewHTTPClient(HTTPClientConfig{}))
return client, nil
}
// SetHTTPClient sets the HTTP client that will be used to call OSRM.
func (osrm *OSRMClient) SetHTTPClient(client HTTPClient) {
if client == nil {
panic("http client can't be nil")
}
osrm.client = client
}
// get calls the given URL and parses the response.
func (osrm OSRMClient) get(ctx context.Context, url string, out any) error {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
res, err := osrm.client.Do(req)
if err != nil {
return err
}
return json.NewDecoder(res.Body).Decode(out)
}
// applyOpts applys options to the URL.
func (osrm OSRMClient) applyOpts(u *url.URL, opts []Option) {
for i := 0; i < len(opts); i++ {
opts[i].apply(u)
}
}
// buildURLPath builds the path of OSRM's services.
func (req Request) buildURLPath(u url.URL, servicePath string) *url.URL {
path := strings.TrimSuffix(u.Path, "/")
coordinates := "/" + convertSliceToStr(req.Coordinates, ";")
profile := "/" + string(req.Profile)
u.Path = path + servicePath + profile + coordinates + ".json"
return &u
}