package main import ( "fmt" "html/template" "log" "net/http" ) const dashboardHtml = ` HVAC Dashboard

Average humidity: {{ printf "%.1f %%" .Average }}

{{ range $id, $humidity := .Rooms }} {{ end }}
RoomHumidity
{{ $id }}{{ printf "%.1f %%" $humidity }}
` var dashboard = template.Must(template.New("dashboard").Parse(dashboardHtml)) type Dashboard struct { Average Humidity Rooms map[RoomID]Humidity } type DashboardHandler struct { Building } func (h DashboardHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Println(r.Method, r.URL) if r.Method != http.MethodGet { w.WriteHeader(http.StatusMethodNotAllowed) fmt.Fprintf(w, "invalid method: '%s'", r.Method) return } db := newDashboard(h.Building) err := dashboard.Execute(w, db) if err != nil { log.Println(err) } } func newDashboard(b Building) Dashboard { average, ok := b.average() if !ok { average = -1 } rooms := make(map[RoomID]Humidity) for id, record := range b { c := make(chan Humidity) record.getRecent <- c humidity, ok := <-c if !ok { humidity = -1 } rooms[id] = humidity } return Dashboard{average, rooms} }