Generalize cache get with expire param
This commit is contained in:
76
datasources/mtr/bus/busschedule.go
Normal file
76
datasources/mtr/bus/busschedule.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package bus
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/tgckpg/golifehk/utils"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type BusStopSchedules struct {
|
||||
Buses [] Bus `json:"bus"`
|
||||
Suspended string `json:"isSuspended"`
|
||||
}
|
||||
|
||||
type BusSchedule struct {
|
||||
RefreshTime int `json:"appRefreshTimeInSecond,string"`
|
||||
BusStops [] BusStopSchedules `json:"busStop"`
|
||||
}
|
||||
|
||||
func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
|
||||
|
||||
CACHE_PATH := filepath.Join(
|
||||
utils.WORKDIR,
|
||||
"mtr_bsch" + "-" + lang + "-" + routeName + ".json",
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
buff, err := utils.CacheStream( CACHE_PATH, QUERY_FUNC, 60 )
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
schedules := BusSchedule{}
|
||||
err = json.Unmarshal( buff.Bytes(), &schedules )
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &schedules, nil
|
||||
}
|
||||
Reference in New Issue
Block a user