summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2024-11-01 22:25:02 -0400
committerSam Anthony <sam@samanthony.xyz>2024-11-01 22:25:02 -0400
commitb533c08f92ae4dcfe3fb7e7bffc4eda796918382 (patch)
tree8d6dbf2d6e97d6cfb5b67c089db703a68e85e9ba
parent125d883d2380e70aab9a1d63753a1e10fb80032b (diff)
downloadsoen422-b533c08f92ae4dcfe3fb7e7bffc4eda796918382.zip
implement server POST humidity
-rw-r--r--Makefile10
-rw-r--r--server.go21
2 files changed, 25 insertions, 6 deletions
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..8954492
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,10 @@
+SRC = server.go record.go
+
+server: ${SRC}
+ go build $^
+
+fmt:
+ gofmt -l -s -w ${SRC}
+
+clean:
+ rm -f server
diff --git a/server.go b/server.go
index 67d153d..2684c3e 100644
--- a/server.go
+++ b/server.go
@@ -4,6 +4,7 @@ import (
"fmt"
"log"
"net/http"
+ "strconv"
)
const addr = ":9090"
@@ -16,7 +17,8 @@ func newHumidityHandler() humidityHandler {
return humidityHandler{newRecord[float32]()}
}
-func (h *humidityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+func (h humidityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ log.Println(r.Method, r.URL)
switch r.Method {
case http.MethodGet:
h.get(w, r)
@@ -28,7 +30,7 @@ func (h *humidityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
-func (h *humidityHandler) get(w http.ResponseWriter, r *http.Request) {
+func (h humidityHandler) get(w http.ResponseWriter, r *http.Request) {
c := make(chan float32)
h.humidity.getRecent <- c
humidity, ok := <-c
@@ -37,15 +39,22 @@ func (h *humidityHandler) get(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "no humidity data stored on server")
return
}
- fmt.Fprintf(w, "%f", humidity)
+ fmt.Fprintf(w, "%.2f", humidity)
}
-func (h *humidityHandler) post(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusNotImplemented)
+func (h humidityHandler) post(w http.ResponseWriter, r *http.Request) {
+ query := r.URL.RawQuery
+ humidity, err := strconv.ParseFloat(query, 32)
+ if err != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ fmt.Fprintf(w, "invalid query string: '%s'", query)
+ return
+ }
+ h.humidity.put <- float32(humidity)
}
func main() {
- http.Handle("/humidity", new(humidityHandler))
+ http.Handle("/humidity", newHumidityHandler())
fmt.Printf("Listening on %s...\n", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}