-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
71 lines (65 loc) · 1.74 KB
/
controller.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 mdrc
import (
"fmt"
"net/http"
"os/exec"
"path"
"strconv"
"github.com/go-logr/logr"
)
type Controller struct {
logger logr.Logger
commands *Commands
html *HTML
}
func NewController(l logr.Logger, c *Commands, h *HTML) *Controller {
return &Controller{
logger: l.WithName("controller"),
commands: c,
html: h,
}
}
// HandleHTML handles the endpoint that exposes the HTML part.
func (c *Controller) HandleHTML() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c.logger.Info("serving", "path", r.URL.Path)
rendered := c.html.Rendered()
_, err := fmt.Fprint(w, rendered)
if err != nil {
c.logger.Error(err, "unable to write", "html", rendered)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
// HandleCommand handles the endpoint that exposes the commands.
func (c *Controller) HandleCommand() func(http.ResponseWriter, *http.Request) {
return func(writer http.ResponseWriter, request *http.Request) {
c.logger.Info("serving", "path", request.URL.Path)
p := path.Base(request.URL.Path)
i, err := strconv.Atoi(p)
if err != nil {
c.logger.Error(err, "base", p)
writer.WriteHeader(http.StatusBadRequest)
return
}
if !c.commands.Valid(i) {
c.logger.Error(err, "wrong command index", "index", i)
writer.WriteHeader(http.StatusBadRequest)
return
}
command := string(c.commands.Command(i))
out, err := exec.Command("sh", "-c", command).Output()
if err != nil {
c.logger.Error(err, "command", command)
writer.WriteHeader(http.StatusInternalServerError)
return
}
_, err = writer.Write(out)
if err != nil {
c.logger.Error(err, "write", command)
writer.WriteHeader(http.StatusInternalServerError)
return
}
}
}