summaryrefslogtreecommitdiffstats
path: root/server/target.go
blob: 2d7ca808a0abf3df7a267e58395e2e8b1853616a (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
package main

import (
	"fmt"
	"github.com/sam-rba/share"
	"log"
	"net/http"
	"strconv"
)

type TargetHumidityHandler struct {
	target share.Val[Humidity]
}

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) {
	fmt.Fprintf(w, "%.2f", h.target.Get())
}

func (h TargetHumidityHandler) post(w http.ResponseWriter, r *http.Request) {
	target, err := strconv.ParseFloat(r.URL.RawQuery, 32)
	if err != nil {
		badRequest(w, "invalid humidity: '%s'", r.URL.RawQuery)
		return
	}

	h.target.Set <- Humidity(target)
}