summaryrefslogtreecommitdiffstats
path: root/server
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2024-11-04 11:35:42 -0500
committerSam Anthony <sam@samanthony.xyz>2024-11-04 11:35:42 -0500
commit45241dba622580d1a7a76d9caf42b5603bd9e630 (patch)
tree3b80318546b17abb9ec1fdd49962dbdf971f0544 /server
parent64912a13d01896ed73a88097e4fa1d93a5e45a6a (diff)
downloadsoen422-45241dba622580d1a7a76d9caf42b5603bd9e630.zip
server: handle /target_humidity
Diffstat (limited to 'server')
-rw-r--r--server/server.go39
1 files changed, 39 insertions, 0 deletions
diff --git a/server/server.go b/server/server.go
index e1fecb8..065bf0b 100644
--- a/server/server.go
+++ b/server/server.go
@@ -6,6 +6,7 @@ import (
"net/http"
"net/url"
"strconv"
+ "sync"
)
const addr = ":9090"
@@ -22,11 +23,17 @@ type HumidityHandler struct {
rooms map[RoomID]Record[Humidity]
}
+type TargetHumidityHandler struct {
+ mu sync.Mutex
+ target Humidity
+}
+
func main() {
humidityHandler := newHumidityHandler(rooms)
defer humidityHandler.Close()
http.Handle("/humidity", humidityHandler)
+ http.Handle("/target_humidity", new(TargetHumidityHandler))
fmt.Printf("Listening on %s...\n", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
@@ -118,6 +125,38 @@ func (h HumidityHandler) average() (Humidity, bool) {
return sum / Humidity(nRooms), true
}
+func (h *TargetHumidityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ log.Println(r.Method, r.URL)
+ switch r.Method {
+ case http.MethodGet:
+ h.get(w, r)
+ case http.MethodPost:
+ h.post(w, r)
+ default:
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ fmt.Fprintf(w, "invalid method: '%s'", r.Method)
+ }
+}
+
+func (h *TargetHumidityHandler) get(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ fmt.Fprintf(w, "%.2f", h.target)
+}
+
+func (h *TargetHumidityHandler) post(w http.ResponseWriter, r *http.Request) {
+ target, err := strconv.ParseFloat(r.URL.RawQuery, 32)
+ if err != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ fmt.Fprintf(w, "invalid humidity: '%s'", r.URL.RawQuery)
+ return
+ }
+
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.target = Humidity(target)
+}
+
// Parse the value associated with each key in the query string. Returns a map of
// keys and values, or error if one of the keys is missing, or if there is no value
// associated with one of the keys.