forked from matthewmueller/joy
/
livereload.go
85 lines (67 loc) · 1.57 KB
/
livereload.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
82
83
84
85
package livereload
import (
"fmt"
"net/http"
"sync"
"github.com/julienschmidt/httprouter"
)
var _ http.Handler = (*Server)(nil)
// New livereload server
func New(port int) *Server {
srv := &Server{}
router := httprouter.New()
srv.router = router
router.HandlerFunc("GET", "/livereload.js", srv.serveJS)
router.HandlerFunc("GET", "/livereload", srv.serveWS)
srv.mu = &sync.RWMutex{}
srv.conns = map[*conn]struct{}{}
srv.js = fmt.Sprintf(js, port)
return srv
}
// Server struct
type Server struct {
router *httprouter.Router
js string
// protects the connections
mu *sync.RWMutex
conns map[*conn]struct{}
}
// Reload a file
func (s *Server) Reload(file string) error {
s.mu.RLock()
defer s.mu.RUnlock()
for conn := range s.conns {
conn.Reload(file)
}
return nil
}
// ServeHTTP implements the http.Handler interface
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
// serveJS serves the client
func (s *Server) serveJS(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
w.Write([]byte(s.js))
}
// serveWS serves the websocket
func (s *Server) serveWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrade(r.Context(), w, r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// add the connection and defer it's removal
s.mu.Lock()
s.conns[conn] = struct{}{}
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.conns, conn)
s.mu.Unlock()
}()
// wait until the connection errors out
if err := conn.Wait(); err != nil {
return
}
}