-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
305 lines (278 loc) · 7.65 KB
/
Copy pathserver.go
File metadata and controls
305 lines (278 loc) · 7.65 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"syscall"
ll "github.com/grimdork/loglines"
)
var signalMap = map[string]syscall.Signal{
"hup": syscall.SIGHUP,
"usr1": syscall.SIGUSR1,
"usr2": syscall.SIGUSR2,
"quit": syscall.SIGQUIT,
}
// serve starts the HTTP server on addr. If the port is in use it logs a warning
// and returns without starting the server.
func serve(app *App, addr string) {
mux := http.NewServeMux()
mux.HandleFunc("/api/status", handleStatus(app))
mux.HandleFunc("/api/env", handleEnv(app))
mux.HandleFunc("/api/env/load", handleEnvLoad(app))
mux.HandleFunc("/api/env/add", handleEnvAdd(app))
mux.HandleFunc("/api/env/remove/", handleEnvRemove(app))
mux.HandleFunc("/api/env/apply", handleEnvApply(app))
mux.HandleFunc("/api/events", handleEvents(app))
mux.HandleFunc("/api/restart", handleRestart(app))
mux.HandleFunc("/api/stop", handleStop(app))
mux.HandleFunc("/api/quit", handleQuit(app))
mux.HandleFunc("/api/signal/", handleSignal(app))
mux.HandleFunc("/api/build", handleBuild(app))
mux.HandleFunc("/api/pause", handlePause(app))
mux.Handle("/", webHandler())
srv := &http.Server{
Addr: addr,
Handler: mux,
}
ln, err := net.Listen("tcp", addr)
if err != nil {
ll.Err("Web server: %s (running without web interface)", err.Error())
return
}
go func() {
<-app.quit
srv.Close()
}()
ll.Msg("Web server: http://localhost%s", addr)
srv.Serve(ln)
ln.Close()
}
func handleStatus(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, app.Status())
}
}
func handleEnv(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
writeJSON(w, map[string]interface{}{
"current": app.EnvEntries(),
"pending": app.PendingEnvEntries(),
})
case http.MethodPut:
var req struct {
Vars []string `json:"vars"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
app.SetPendingEnv(req.Vars)
writeJSON(w, map[string]interface{}{
"pending": app.PendingEnvEntries(),
})
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
}
func handleEnvLoad(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Path string `json:"path"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := app.LoadEnvFile(req.Path); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
writeJSON(w, map[string]interface{}{
"current": app.EnvEntries(),
"pending": app.PendingEnvEntries(),
})
}
}
func handleEnvAdd(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Key string `json:"key"`
Value string `json:"value"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Key == "" {
http.Error(w, "key is required", http.StatusBadRequest)
return
}
app.AddPendingEnv(req.Key, req.Value)
writeJSON(w, map[string]interface{}{
"pending": app.PendingEnvEntries(),
})
}
}
func handleEnvRemove(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
key, err := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/api/env/remove/"))
if err != nil || key == "" {
http.Error(w, "invalid key", http.StatusBadRequest)
return
}
app.RemovePendingEnv(key)
writeJSON(w, map[string]interface{}{
"pending": app.PendingEnvEntries(),
})
}
}
func handleEnvApply(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
go app.ApplyEnv()
writeJSON(w, map[string]string{"status": "applying"})
}
}
func handleEvents(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming not supported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
ch := app.logBuf.Subscribe()
defer app.logBuf.Unsubscribe(ch)
// Send backlog of last 200 lines
for _, entry := range app.logBuf.Lines(200) {
writeSSE(w, flusher, SSEEvent{
Type: "log",
Time: entry.Time,
Line: entry.Line,
})
}
for {
select {
case evt := <-ch:
if err := writeSSE(w, flusher, evt); err != nil {
return
}
case <-r.Context().Done():
return
}
}
}
}
func handleRestart(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
go app.Restart()
writeJSON(w, map[string]string{"status": "restarting"})
}
}
func handleStop(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
go app.Stop()
writeJSON(w, map[string]string{"status": "stopped"})
}
}
func handleQuit(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
writeJSON(w, map[string]string{"status": "shutting down"})
go app.Quit()
}
}
func handleSignal(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
name := strings.TrimPrefix(r.URL.Path, "/api/signal/")
sig, ok := signalMap[name]
if !ok {
http.Error(w, "unknown signal: "+name, http.StatusBadRequest)
return
}
app.Signal(sig)
writeJSON(w, map[string]string{"status": "signalled", "signal": name})
}
}
func handleBuild(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Cmd string `json:"cmd"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err == nil && req.Cmd != "" {
app.SetBuildCmd(req.Cmd)
}
go app.Build()
writeJSON(w, map[string]string{"status": "building"})
}
}
func handlePause(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
app.TogglePause()
writeJSON(w, map[string]interface{}{
"watching": app.Status()["watching"],
})
}
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
func writeSSE(w http.ResponseWriter, flusher http.Flusher, evt SSEEvent) error {
data, err := json.Marshal(evt)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", evt.Type, string(data))
if err != nil {
return err
}
flusher.Flush()
return nil
}