golifehk/datasources/mtr/bus/busschedule.go

78 lines
1.8 KiB
Go
Raw Normal View History

2022-09-14 09:12:48 +00:00
package bus
2022-09-13 13:42:51 +00:00
import (
2022-09-14 09:12:48 +00:00
"bytes"
2022-09-13 13:42:51 +00:00
"encoding/json"
2022-09-14 09:12:48 +00:00
"io"
"net/http"
"path/filepath"
"github.com/tgckpg/golifehk/utils"
2022-09-13 13:42:51 +00:00
)
type Location struct {
latitude float32
longitude float32
}
type Bus struct {
ETA int `json:"arrivalTimeInSecond,string"`
ETAText string `json:"arrivalTimeText"`
BusId string `json:"busId"`
BusLocation Location `json:"busLocation"`
ETD string `json:"departureTimeInSecond"`
ETDText string `json:"departureTimeText"`
Delayed string `json:"isDelayed"`
Scheduled string `json:"isScheduled"`
LineRef string `json:"lineRef"`
}
2022-09-14 13:21:39 +00:00
type BusStopBuses struct {
2022-09-13 13:42:51 +00:00
Buses [] Bus `json:"bus"`
2022-09-14 13:21:39 +00:00
BusStopId string `json:"busStopId"`
2022-09-13 13:42:51 +00:00
Suspended string `json:"isSuspended"`
}
type BusSchedule struct {
RefreshTime int `json:"appRefreshTimeInSecond,string"`
2022-09-14 13:21:39 +00:00
BusStops [] BusStopBuses `json:"busStop"`
2022-09-13 13:42:51 +00:00
}
func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
2022-09-14 09:12:48 +00:00
CACHE_PATH := filepath.Join(
utils.WORKDIR,
"mtr_bsch" + "-" + lang + "-" + routeName + ".json",
2022-09-13 13:42:51 +00:00
)
2022-09-14 09:12:48 +00:00
QUERY_FUNC := func() ( io.ReadCloser, error ) {
// Query Remote
values := map[string]string { "language": lang , "routeName": routeName }
jsonValue, _ := json.Marshal(values)
resp, err := http.Post(
"https://rt.data.gov.hk/v1/transport/mtr/bus/getSchedule",
"application/json",
bytes.NewBuffer( jsonValue ),
)
if err != nil {
return nil, err
}
return resp.Body, nil
2022-09-13 13:42:51 +00:00
}
2022-09-14 09:12:48 +00:00
buff, err := utils.CacheStream( CACHE_PATH, QUERY_FUNC, 60 )
2022-09-13 13:42:51 +00:00
if err != nil {
return nil, err
}
schedules := BusSchedule{}
2022-09-14 09:12:48 +00:00
err = json.Unmarshal( buff.Bytes(), &schedules )
2022-09-13 13:42:51 +00:00
if err != nil {
return nil, err
}
return &schedules, nil
}