From 46df54614697e7b8ad6b1c48a984261be40a849b Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sun, 27 Mar 2016 22:18:13 +0200 Subject: [PATCH] Added JSON version of dashboard --- main.go | 2 ++ structs.go | 4 ++++ web_handlers.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/main.go b/main.go index 4a4d3bf..068b30b 100644 --- a/main.go +++ b/main.go @@ -40,6 +40,8 @@ func main() { Methods("GET") r.HandleFunc("/create", handleCreateRandomDashboard). Methods("GET") + r.HandleFunc("/{dashid}.json", handleDisplayDashboardJSON). + Methods("GET") r.HandleFunc("/{dashid}", handleDisplayDashboard). Methods("GET") diff --git a/structs.go b/structs.go index a344e90..5fb03ef 100644 --- a/structs.go +++ b/structs.go @@ -169,6 +169,10 @@ func (dm *dashboardMetric) StatisticalStatus() string { } func (dm *dashboardMetric) PreferredStatus() string { + if dm.Meta.LastUpdate.Before(time.Now().Add(-1 * time.Duration(dm.Freshness) * time.Second)) { + return "Unknown" + } + if dm.IgnoreMAD { return dm.Status } diff --git a/web_handlers.go b/web_handlers.go index 43c1807..0b155c4 100644 --- a/web_handlers.go +++ b/web_handlers.go @@ -51,6 +51,54 @@ func handleDisplayDashboard(res http.ResponseWriter, req *http.Request) { }, res) } +func handleDisplayDashboardJSON(res http.ResponseWriter, req *http.Request) { + params := mux.Vars(req) + dash, err := loadDashboard(params["dashid"], store) + if err != nil { + dash = &dashboard{APIKey: generateAPIKey(), Metrics: dashboardMetrics{}} + } + + response := struct { + APIKey string `json:"api_key,omitempty"` + Metrics []struct { + ID string `json:"id"` + Title string `json:"title"` + Description string `json:"description"` + Status string `json:"status"` + Value float64 `json:"value"` + LastUpdate time.Time `json:"last_update"` + } `json:"metrics"` + }{} + + // Filter out expired metrics + for _, m := range dash.Metrics { + if m.Meta.LastUpdate.After(time.Now().Add(time.Duration(m.Expires*-1) * time.Second)) { + response.Metrics = append(response.Metrics, struct { + ID string `json:"id"` + Title string `json:"title"` + Description string `json:"description"` + Status string `json:"status"` + Value float64 `json:"value"` + LastUpdate time.Time `json:"last_update"` + }{ + ID: m.MetricID, + Title: m.Title, + Description: m.Description, + Status: m.PreferredStatus(), + Value: m.Value, + LastUpdate: m.Meta.LastUpdate, + }) + } + } + + if len(response.Metrics) == 0 { + response.APIKey = dash.APIKey + } + + res.Header().Set("Content-Type", "application/json") + json.NewEncoder(res).Encode(response) +} + func handleDeleteDashboard(res http.ResponseWriter, req *http.Request) { params := mux.Vars(req) dash, err := loadDashboard(params["dashid"], store)