-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
92 lines (75 loc) · 2.14 KB
/
client.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 transdevclient
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type Client struct {
client *http.Client
}
func NewClient() Client {
httpClient := http.DefaultClient
return Client{client: httpClient}
}
// Search searches for Stops and Routes with query in their name. It
// returns a SearchResult containing matching Stops and Routes.
//
// Note that only a limited amount of objects is returned in the
// SearchResult. Make your query as specific as possible for a higher
// probability to find the objects you need.
func (c *Client) Search(query string) (SearchResult, error) {
req, err := http.NewRequest(http.MethodGet, "https://www.breng.nl/api/travelplanner/search", nil)
if err != nil {
return SearchResult{}, err
}
q := req.URL.Query()
q.Add("text", query)
req.URL.RawQuery = q.Encode()
resp, err := c.client.Do(req)
if err != nil {
return SearchResult{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return SearchResult{}, err
}
searchResponse := SearchResponse{}
err = json.Unmarshal(body, &searchResponse)
if err != nil {
return SearchResult{}, err
}
return searchResponse.Result.Results, nil
}
func (c *Client) Departures(quayID, name, town string) ([]Departure, error) {
req, err := http.NewRequest(http.MethodGet, "https://www.breng.nl/api/travelplanner/quays/departures", nil)
if err != nil {
return []Departure{}, err
}
q := req.URL.Query()
q.Add("stop", fmt.Sprintf("{'quayid': '%s', 'name': '%s', 'town': '%s'}", quayID, name, town))
req.URL.RawQuery = q.Encode()
resp, err := c.client.Do(req)
if err != nil {
return []Departure{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return []Departure{}, err
}
departuresResponse := DeparturesResponse{}
err = json.Unmarshal(body, &departuresResponse)
if err != nil {
return []Departure{}, err
}
if len(departuresResponse.Results) == 0 {
return []Departure{}, errors.New("no departures found")
}
if len(departuresResponse.Results) > 1 {
return []Departure{}, errors.New("too many departures found")
}
return departuresResponse.Results[0].Departures, nil
}