2021-02-14 16:55:56 -09:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-03-07 16:43:51 -09:00
|
|
|
"git.binarythought.com/cdramey/alrm/api"
|
2021-03-07 18:40:45 -09:00
|
|
|
"net/http"
|
2021-02-14 16:55:56 -09:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
switch r.URL.Path {
|
2021-03-01 07:26:27 -09:00
|
|
|
case "/api":
|
2021-03-07 18:40:45 -09:00
|
|
|
if err := r.ParseForm(); err != nil {
|
|
|
|
http.Error(w, fmt.Sprintf("form parse error: %s", err.Error()),
|
|
|
|
http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c := r.FormValue("cmd")
|
2021-03-01 07:26:27 -09:00
|
|
|
if c == "" {
|
|
|
|
http.Error(w, "no command given", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2021-03-07 16:43:51 -09:00
|
|
|
cmd, err := api.ParseCommand([]byte(c))
|
2021-03-01 07:26:27 -09:00
|
|
|
if err != nil {
|
2021-03-07 18:40:45 -09:00
|
|
|
http.Error(w, fmt.Sprintf("command parse error: %s", err.Error()),
|
2021-03-01 07:26:27 -09:00
|
|
|
http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = cmd.Validate(s.config.APIKey)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch cmd.Command {
|
|
|
|
case "shutdown":
|
|
|
|
s.shutdownc <- false
|
|
|
|
|
|
|
|
case "restart":
|
|
|
|
s.shutdownc <- true
|
|
|
|
|
|
|
|
default:
|
|
|
|
http.Error(w, fmt.Sprintf("unknown command: %s", cmd.Command),
|
|
|
|
http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
|
2021-02-14 16:55:56 -09:00
|
|
|
default:
|
2021-03-01 07:26:27 -09:00
|
|
|
http.Error(w, "File not found", http.StatusNotFound)
|
2021-02-14 16:55:56 -09:00
|
|
|
}
|
|
|
|
}
|