-
Notifications
You must be signed in to change notification settings - Fork 14
/
middleware.go
81 lines (64 loc) · 1.92 KB
/
middleware.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
package command
import (
"encoding/json"
"net/http"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
var (
_ caddy.Module = (*Middleware)(nil)
_ caddy.Provisioner = (*Middleware)(nil)
_ caddy.Validator = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
)
func init() {
caddy.RegisterModule(Middleware{})
}
// Middleware implements an HTTP handler that runs shell command.
type Middleware struct {
Cmd
}
// CaddyModule returns the Caddy module information.
func (Middleware) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.exec",
New: func() caddy.Module { return new(Middleware) },
}
}
// Provision implements caddy.Provisioner.
func (m *Middleware) Provision(ctx caddy.Context) error { return m.Cmd.provision(ctx, m) }
// Validate implements caddy.Validator
func (m Middleware) Validate() error { return m.Cmd.validate() }
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
// replace per-request placeholders
argv := make([]string, len(m.Args))
for index, argument := range m.Args {
argv[index] = repl.ReplaceAll(argument, "")
}
err := m.run(argv)
if m.PassThru {
if err != nil {
m.log.Error(err.Error())
}
return next.ServeHTTP(w, r)
}
var resp struct {
Status string `json:"status,omitempty"`
Error string `json:"error,omitempty"`
}
if err == nil {
resp.Status = "success"
} else {
w.WriteHeader(http.StatusInternalServerError)
resp.Error = err.Error()
}
w.Header().Add("content-type", "application/json")
return json.NewEncoder(w).Encode(resp)
}
// Cleanup implements caddy.Cleanup
// TODO: ensure all running processes are terminated.
func (m *Middleware) Cleanup() error {
return nil
}