Bendodroid
4b41acfa7b
- Move components to separate packages - Fix HTTP header for 401 response - Add documentation
88 lines
2.3 KiB
Go
88 lines
2.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
|
|
)
|
|
|
|
func Root(resp *types.SpaceAPIResponseV14) func(http.ResponseWriter, *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// Check if GET method
|
|
if r.Method != http.MethodGet {
|
|
log.Println("Wrong METHOD from", r.RemoteAddr)
|
|
w.Header().Set("Allow", http.MethodGet)
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
// Serialize response
|
|
response, err := json.Marshal(resp)
|
|
if err != nil {
|
|
log.Println("Failed to serialize JSON response:", err)
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// Respond with OK
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write(response)
|
|
}
|
|
}
|
|
|
|
func StateOpen(
|
|
validUsername, validPassword string, 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 || username != validUsername || password != validPassword {
|
|
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")
|
|
}
|
|
}
|