-
Notifications
You must be signed in to change notification settings - Fork 0
/
commute.go
71 lines (59 loc) · 1.54 KB
/
commute.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
package api
import (
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/tjhorner/dash/api/maps"
"github.com/tjhorner/dash/util"
)
// CommuteAPI is the API that handles the Commute panel
type CommuteAPI struct {
MapsKey string
FromAddress string
ToAddress string
latestTime *timeResponse
timeFrom time.Time
}
type timeResponse struct {
Time string `json:"time"`
}
// Configure implements API.Configure
func (api *CommuteAPI) Configure() {
api.MapsKey = util.GetEnv("DASH_COMMUTE_GMAPS_KEY", "")
api.FromAddress = util.GetEnv("DASH_COMMUTE_FROM_ADDRESS", "")
api.ToAddress = util.GetEnv("DASH_COMMUTE_TO_ADDRESS", "")
}
// Prefix implements API.Prefix
func (api *CommuteAPI) Prefix() string {
return "/api/commute"
}
// Route implements API.Route
func (api *CommuteAPI) Route(router *mux.Router) {
router.HandleFunc("/time", api.getTime).Methods("GET")
}
// GET /time
func (api *CommuteAPI) getTime(w http.ResponseWriter, r *http.Request) {
// simple caching (1min)
if time.Now().Sub(api.timeFrom) <= time.Minute {
respondJSON(api.latestTime, w, r)
return
}
dmr := &maps.DistanceMatrixRequest{
Key: api.MapsKey,
Origins: api.FromAddress,
Destinations: api.ToAddress,
TravelMode: maps.TravelModeTransit,
TransitMode: maps.TransitModeSubway,
}
dm, err := maps.GetDistanceMatrix(dmr)
if err != nil {
respondError(err, "ERR_MAPS_RESPONSE", w, r)
return
}
resp := timeResponse{
Time: dm.Rows[0].Elements[0].Duration.Text,
}
api.latestTime = &resp
api.timeFrom = time.Now()
respondJSON(resp, w, r)
}