From f792d6dd242dfa3ea9dc6901b01b451257d5b46b Mon Sep 17 00:00:00 2001 From: andig Date: Wed, 25 Dec 2019 16:26:36 +0100 Subject: [PATCH] Use map instead of array for all devices apis (#60) --- server/http.go | 9 +++++---- server/json.go | 6 ++---- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/server/http.go b/server/http.go index 216a9174..6a107773 100644 --- a/server/http.go +++ b/server/http.go @@ -58,7 +58,8 @@ func (h *Httpd) allDevicesHandler( ) func(http.ResponseWriter, *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ids := h.mc.SortedIDs() - res := make([]apiData, 0) + res := make(map[string]apiData) + for _, id := range ids { readings, err := readingsProvider(id) if err != nil { @@ -66,8 +67,8 @@ func (h *Httpd) allDevicesHandler( continue } - data := apiData{device: id, readings: readings} - res = append(res, data) + data := apiData{readings: readings} + res[id] = data } if len(res) == 0 { @@ -102,7 +103,7 @@ func (h *Httpd) singleDeviceHandler( return } - data := apiData{device: id, readings: readings} + data := apiData{readings: readings} w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(data); err != nil { diff --git a/server/json.go b/server/json.go index 14f1f828..02ae28fa 100644 --- a/server/json.go +++ b/server/json.go @@ -7,17 +7,15 @@ import ( "sort" ) -// apiData combines readings with associated device id for JSON encoding -// using kvslice it ensured order export of the readings map +// apiData combines readings with timestamps and uses +// kvslice to ensure ordered export of the readings map type apiData struct { - device string readings *Readings } // MarshalJSON creates device api json for export func (d apiData) MarshalJSON() ([]byte, error) { res := kvslice{ - {"Device", d.device}, {"Timestamp", d.readings.Timestamp}, {"Unix", d.readings.Timestamp.Unix()}, }