-
Notifications
You must be signed in to change notification settings - Fork 3
/
control.go
78 lines (69 loc) · 1.59 KB
/
control.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
package graceful
import (
"context"
"encoding/json"
"net"
"net/http"
)
type controlServer struct {
server *http.Server
}
type commandResponse struct {
Ok bool `json:"ok,omitempty"`
Err string `json:"err,omitempty"`
}
func (s *controlServer) Serve(l net.Listener) error {
err := s.server.Serve(l)
if err != http.ErrServerClosed {
return err
}
return nil
}
func (s *controlServer) Shutdown(ctx context.Context) error {
return s.server.Shutdown(ctx)
}
// NewControlServer creates a control command server
func NewControlServer() Server {
h := func(writer http.ResponseWriter, request *http.Request) {
var err error
defer func() {
if err != nil {
lg.Printf("control server error: %v", err)
}
}()
// process commands
var response commandResponse
switch request.RequestURI {
case "/shutdown":
CommandChannel <- CtrlCommand{Command: CommandShutdown}
case "/restart":
cmd := CtrlCommand{Command: CommandRestart, ErrorChannel: make(chan error)}
CommandChannel <- cmd
if e := <-cmd.ErrorChannel; e != nil {
response.Err = e.Error()
}
default:
response.Err = "unknown command"
}
// write result back
if len(response.Err) == 0 {
response.Ok = true
}
var data []byte
data, err = json.Marshal(response)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
return
}
writer.Header().Add("Content-Type", "application/json; charset=utf-8")
writer.WriteHeader(http.StatusOK)
_, err = writer.Write(data)
}
m := http.NewServeMux()
m.HandleFunc("/", h)
return &controlServer{
server: &http.Server{
Handler: m,
},
}
}