summaryrefslogtreecommitdiffstats
path: root/server.go
blob: 2684c3e216e5b3298e940b6e3bb6fd32bdd09518 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main

import (
	"fmt"
	"log"
	"net/http"
	"strconv"
)

const addr = ":9090"

type humidityHandler struct {
	humidity Record[float32]
}

func newHumidityHandler() humidityHandler {
	return humidityHandler{newRecord[float32]()}
}

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)
	case http.MethodPost:
		h.post(w, r)
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
		fmt.Fprintf(w, "invalid method: '%s'", r.Method)
	}
}

func (h humidityHandler) get(w http.ResponseWriter, r *http.Request) {
	c := make(chan float32)
	h.humidity.getRecent <- c
	humidity, ok := <-c
	if !ok {
		w.WriteHeader(http.StatusGone)
		fmt.Fprintf(w, "no humidity data stored on server")
		return
	}
	fmt.Fprintf(w, "%.2f", humidity)
}

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", newHumidityHandler())
	fmt.Printf("Listening on %s...\n", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}