/
srv-POST-os.go
71 lines (65 loc) · 1.58 KB
/
srv-POST-os.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
package live
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"time"
)
func handleOSRequest(w http.ResponseWriter, req *http.Request) error {
rawbody, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
reqCmd := struct {
Cmd string `json:"cmd"`
}{}
if err := json.Unmarshal(rawbody, &reqCmd); err != nil {
return err
}
log.Println("Os Request ", reqCmd.Cmd)
var cmdStr string
switch reqCmd.Cmd {
case "reboot":
cmdStr = "sudo reboot"
log.Println("Reboot request received")
execCmdInBackground(cmdStr)
case "shutdown":
cmdStr = "sudo shutdown"
log.Println("Shutdown request received")
execCmdInBackground(cmdStr)
case "service-restart":
// NOTE: stop or start make no sense because after a stop
// no more commands could be handled.
// For developement use the console
log.Println("Service restart request received")
cmdStr = "sudo systemctl restart live-omxctrl"
execCmdInBackground(cmdStr)
case "kill-all-omx":
log.Println("Kill all Omxplayer")
cmdStr = "sudo killall omxplayer.bin"
execCmdInBackground(cmdStr)
default:
return fmt.Errorf("Command not recognized %s", reqCmd.Cmd)
}
resObj := struct {
Msg string `json:"msg"`
}{
Msg: fmt.Sprintf("Cmd %q submitted", cmdStr),
}
return writeResponse(w, resObj)
}
func execCmdInBackground(cmdStr string) {
go func() {
time.Sleep(2 * time.Second)
cmdExec := exec.Command("bash", "-c", cmdStr)
out, err := cmdExec.Output()
if err != nil {
log.Println("Error on shutdown: ", err)
}
res := string(out)
log.Println("Command executed ", cmdStr, res)
}()
}