-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (69 loc) · 2.05 KB
/
main.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"embed"
"fmt"
"html/template"
"io/fs"
"net/http"
"os/exec"
"github.com/rs/zerolog/log"
)
//go:embed static
var staticFiles embed.FS
//go:embed templates/index.html templates/success.html
var templatesFS embed.FS
func main() {
http.HandleFunc("/", serveHTML)
http.HandleFunc("/success", serveSuccessHTML)
http.HandleFunc("/api/reboot", rebootRaspberryPi)
staticFS, err := fs.Sub(staticFiles, "static")
if err != nil {
panic(err)
}
http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.FS(staticFS))))
log.Info().Msg("Starting server on port 3001...")
if err := http.ListenAndServe(":3001", nil); err != nil {
panic(err)
}
}
func serveHTML(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFS(templatesFS, "templates/index.html")
if err != nil {
log.Error().Err(err).Msg("Failed to load index template")
http.Error(w, "Failed to load template", http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, nil)
if err != nil {
log.Error().Err(err).Msg("Failed to render index template")
http.Error(w, "Failed to render template", http.StatusInternalServerError)
return
}
}
func serveSuccessHTML(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFS(templatesFS, "templates/success.html")
if err != nil {
log.Error().Err(err).Msg("Failed to load success template")
http.Error(w, "Failed to load template", http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, nil)
if err != nil {
log.Error().Err(err).Msg("Failed to render success template")
http.Error(w, "Failed to render template", http.StatusInternalServerError)
return
}
}
func rebootRaspberryPi(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
cmd := exec.Command("sudo", "shutdown", "-r")
if err := cmd.Run(); err != nil {
log.Error().Err(err).Msg("Failed to reboot Pi")
http.Error(w, "Failed to reboot Pi", http.StatusInternalServerError)
return
}
fmt.Fprint(w, "Rebooting...")
}