First implementation of new config format
- Functionally equivalent to old version at present - Temperature and Humidity sensors not handled yet - Moved HTTP handlers around
This commit is contained in:
parent
7bb676887f
commit
b2f62c7bb0
7 changed files with 125 additions and 121 deletions
63
handlers/state.go
Normal file
63
handlers/state.go
Normal file
|
@ -0,0 +1,63 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gitlab.hamburg.ccc.de/ccchh/spaceapid/config"
|
||||
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
|
||||
"gitlab.hamburg.ccc.de/ccchh/spaceapid/util"
|
||||
)
|
||||
|
||||
func StateOpen(
|
||||
authDB config.HTTPBACredentials, validCredentials []config.HTTPBACredentialID,
|
||||
resp *types.SpaceAPIResponseV14,
|
||||
) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Check BasicAuth credentials
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || !util.CheckCredentials(authDB, validCredentials, username, password) {
|
||||
log.Println("Unauthorized request from", r.RemoteAddr)
|
||||
w.Header().Set("WWW-Authenticate", "Basic realm=\"space-api\"")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if PUT method
|
||||
if r.Method != http.MethodPut {
|
||||
log.Println("Wrong METHOD from", r.RemoteAddr)
|
||||
w.Header().Set("Allow", http.MethodPut)
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Read request body
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
log.Println("Failed to read request body from", r.RemoteAddr)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = io.WriteString(w, "Failed reading HTTP request body")
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
newState, err := strconv.ParseBool(string(body))
|
||||
if err != nil {
|
||||
log.Println("Failed to parse request body from", r.RemoteAddr)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = io.WriteString(w, "HTTP request body should either be true or false")
|
||||
return
|
||||
}
|
||||
|
||||
// Set SpaceAPI response values
|
||||
resp.State.Open = newState
|
||||
resp.State.LastChange = time.Now().Unix()
|
||||
|
||||
// Respond with OK
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.WriteString(w, "Update Successful")
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue