-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.go
56 lines (46 loc) · 1.11 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
package main
import (
"log"
"net"
"net/http"
"sync"
)
type ControlServer struct {
SocketPath string
Recorder *Recorder
}
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func (c *ControlServer) ListenAndServe() error {
listener, err := net.Listen("unix", c.SocketPath)
if err != nil {
return err
}
mux := http.NewServeMux()
var last []byte = nil
var lock sync.Mutex
mux.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
c.Recorder.Start()
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/stop", func(w http.ResponseWriter, r *http.Request) {
buf := c.Recorder.Stop()
lock.Lock()
defer lock.Unlock()
last = buf
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/last", func(w http.ResponseWriter, r *http.Request) {
lock.Lock()
defer lock.Unlock()
_, err := w.Write(last)
if err != nil {
log.Printf("http write error: %s", err)
}
})
return http.Serve(listener, logRequest(mux))
}