-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbus.go
74 lines (68 loc) · 1.31 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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"slices"
"strconv"
"time"
)
const tflBase = "https://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1"
type resp []any
type Bus struct {
Number string
ETA time.Time
}
func GetCountdownData(baseUrl string, stop int) ([]Bus, error) {
buses := make([]Bus, 0, 3)
u, err := url.Parse(baseUrl)
if err != nil {
panic(err)
}
args := u.Query()
args.Add("StopCode1", strconv.Itoa(stop))
u.RawQuery = args.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
panic(err)
}
req.Header.Set("User-Agent", "amnon_bus_times/2.0 ([email protected])")
r, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != 200 {
fmt.Println(r.Status)
return nil, fmt.Errorf("bad status %s", r.Status)
}
dec := json.NewDecoder(r.Body)
for {
var b resp
err := dec.Decode(&b)
if err == io.EOF {
break
}
if err != nil {
log.Println(err)
return nil, err
}
if b[0].(float64) != 1 {
continue
}
tnum, ok := b[3].(float64)
if !ok {
continue
}
t := int64(tnum)
tm := time.UnixMilli(t)
buses = append(buses, Bus{b[2].(string), tm})
}
slices.SortFunc(buses, func(a, b Bus) int {
return a.ETA.Compare(b.ETA)
})
return buses, err
}