// vim: shiftwidth=4 tabstop=4 noexpandtab package main import ( "fmt" "log" "net/http" "os/exec" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" ) const ( APP_DATA = "/usr/share/birdscan" ) type WebServer struct { config *WebConfig } type WebConfig struct { BindAddress string `json:"bind_address"` BindPort string `json:"bind_port"` } func NewWebServer() WebServer { server := WebServer{} server.config = &(config.Web) return server } func (server *WebServer) run() { router := chi.NewRouter() router.Use(middleware.Logger) router.Get("/", indexHandler) router.Get("/css/birdscan.css", cssHandler) router.Get("/js/birdscan.js", jsHandler) router.Post("/api/state", stateHandler) router.Post("/api/single_picture", singlePictureHandler) router.Post("/api/reboot", rebootHandler) router.Post("/api/poweroff", poweroffHandler) log.Println("Binding to 'http://" + server.config.BindAddress + ":" + server.config.BindPort + "'") log.Fatal(http.ListenAndServe(server.config.BindAddress + ":" + server.config.BindPort, router)) } func indexHandler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, fmt.Sprintf("%s/html/index.html", APP_DATA)) } func cssHandler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, fmt.Sprintf("%s/css/birdscan.css", APP_DATA)) } func jsHandler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, fmt.Sprintf("%s/js/birdscan.js", APP_DATA)) } func stateHandler(w http.ResponseWriter, r *http.Request) { known_state := r.FormValue("known_state") w.Write([]byte(fmt.Sprintf("%s", camera.statemachine.GetStateOnChange(known_state)))) } func singlePictureHandler(w http.ResponseWriter, r *http.Request) { camera.statemachine.SendEvent("take_single_picture") fmt.Fprintf(w, http.StatusText(http.StatusOK)) } func rebootHandler(w http.ResponseWriter, r *http.Request) { log.Println("starting reboot") if config.Flag.Debug { log.Println("Skipping reboot because of debug mode") } else { cmd := exec.Command("/usr/bin/sudo", "/usr/bin/reboot") err := cmd.Run() if err != nil { log.Print(err) fmt.Fprintf(w, http.StatusText(http.StatusForbidden)) return } } fmt.Fprintf(w, http.StatusText(http.StatusOK)) } func poweroffHandler(w http.ResponseWriter, r *http.Request) { log.Println("starting poweroff") if config.Flag.Debug { log.Println("Skipping poweroff because of debug mode") } else { cmd := exec.Command("/usr/bin/sudo", "/usr/bin/poweroff") err := cmd.Run() if err != nil { log.Print(err) fmt.Fprintf(w, http.StatusText(http.StatusForbidden)) return } } fmt.Fprintf(w, http.StatusText(http.StatusOK)) }