-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
64 lines (56 loc) · 1.63 KB
/
server.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
package procman
import (
"fmt"
"net/http"
)
// ProcManServer represents an HTTP server that receives requests to start,
// stop, or restart a process manager.
// It contains a channel to send the requests to the process manager.
// It implements the http.Handler interface.
type ProcManServer struct {
ChReq chan<- Request
}
// Statically verify that ProcManServer implements the http.Handler interface.
var _ http.Handler = (*ProcManServer)(nil)
// ServeHTTP handles HTTP requests to start, stop, or restart a process manager.
// It reads the action from the request path and sends a request to the process
// manager.
// It writes a response with the status code 200 if the request was successful.
// If the request fails, it writes a response with the status code 500 and the
// error message.
func (pms *ProcManServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var (
action Action
command string
chResp chan error = make(chan error)
)
// Check the request path and set the action accordingly
switch r.URL.Path {
case "/start":
action = ActionStart
command = "start"
case "/stop":
action = ActionStop
command = "stop"
case "/restart":
action = ActionRestart
command = "restart"
default:
http.Error(w, "invalid action", http.StatusBadRequest)
return
}
// Send the request to the process manager
pms.ChReq <- Request{
Action: action,
Response: chResp,
}
// Wait for the response
if err := <-chResp; err != nil {
http.Error(w,
fmt.Sprintf("error: %v", err.Error()),
http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("%v success\n", command)))
}