-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbus.go
99 lines (81 loc) · 2.54 KB
/
bus.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
package mta
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/pkg/errors"
)
type DetailLevel string
const (
StopMonitoringURL = "http://bustime.mta.info/api/siri/stop-monitoring.json"
minimum DetailLevel = "minimum"
basic DetailLevel = "basic"
normal DetailLevel = "normal"
calls DetailLevel = "calls"
)
type BusTimeService interface {
GetStopMonitoring(stopID string) (*StopMonitoringResponse, error)
GetStopMonitoringWithDetailLevel(stopID string, detailLevel DetailLevel) (*StopMonitoringResponse, error)
}
type BusTimeClient struct {
client HTTPClient
apiKey string
userAgent string
}
func NewBusTimeClient(client HTTPClient, apiKey, userAgent string) (*BusTimeClient, error) {
if client == nil {
return nil, ErrClientRequired
}
if apiKey == "" {
return nil, ErrAPIKeyRequired
}
return &BusTimeClient{
apiKey: apiKey,
userAgent: userAgent,
client: client,
}, nil
}
func (c *BusTimeClient) GetStopMonitoring(stopID string) (*StopMonitoringResponse, error) {
return c.GetStopMonitoringWithDetailLevel(stopID, calls)
}
func (c *BusTimeClient) GetStopMonitoringWithDetailLevel(stopID string, detailLevel DetailLevel) (*StopMonitoringResponse, error) {
v := url.Values{}
v.Add("key", c.apiKey)
v.Add("version", "2")
v.Add("OperatorRef", "MTA")
v.Add("MonitoringRef", stopID)
v.Add("StopMonitoringDetailLevel", string(detailLevel))
url := fmt.Sprintf("%s?%s", StopMonitoringURL, v.Encode())
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to create new HTTP request")
}
req.Header.Add("User-Agent", c.userAgent)
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send GetStopMonitoring request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("non 200 response status: %v", resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read GetStopMonitoring response: %v", err)
}
response := StopMonitoringResponse{}
err = json.Unmarshal(body, &response)
if err != nil {
return nil, fmt.Errorf("failed to parse GetStopMonitoring response: %v, body: %s", err, body)
}
if len(response.Siri.ServiceDelivery.VehicleMonitoringDelivery) > 0 {
message := response.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].ErrorCondition.Description
if message == "API key is not authorized." {
return &response, ErrAPIKeyNotAuthorized
}
return &response, errors.New(message)
}
return &response, nil
}