/
lever.go
58 lines (47 loc) · 1.65 KB
/
lever.go
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
package gate
import (
"net/http"
"strconv"
"github.com/go-kit/kit/log/level"
"github.com/xmidt-org/webpa-common/logging"
"github.com/xmidt-org/webpa-common/xhttp"
)
// Lever is an http.Handler which controls the state of a gate.
type Lever struct {
// Gate is the gate this lever controls
Gate Interface
// Parameter is the HTTP parameter, which must be a bool, used to set the state of the gate
Parameter string
}
func (l *Lever) ServeHTTP(response http.ResponseWriter, request *http.Request) {
logger := logging.GetLogger(request.Context())
if err := request.ParseForm(); err != nil {
logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "bad form request", logging.ErrorKey(), err)
xhttp.WriteError(response, http.StatusBadRequest, err)
return
}
v := request.FormValue(l.Parameter)
if len(v) == 0 {
logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "no parameter found", "parameter", l.Parameter)
xhttp.WriteErrorf(response, http.StatusBadRequest, "missing %s parameter", l.Parameter)
return
}
f, err := strconv.ParseBool(v)
if err != nil {
logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "parameter is not a bool", "parameter", l.Parameter, logging.ErrorKey(), err)
xhttp.WriteErrorf(response, http.StatusBadRequest, "the %s parameter must be a bool", l.Parameter)
return
}
var changed bool
if f {
changed = l.Gate.Raise()
} else {
changed = l.Gate.Lower()
}
logger.Log(level.Key(), level.InfoValue(), logging.MessageKey(), "gate update", "open", f, "changed", changed)
if changed {
response.WriteHeader(http.StatusCreated)
} else {
response.WriteHeader(http.StatusOK)
}
}