/
server.go
62 lines (52 loc) · 1.19 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
package browsersync
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"time"
)
const route = "/sync"
// Server serves a REST route the client connects to receive sync messages
type Server struct {
hub *Hub
srv *http.Server
}
// NewServer creates a new Server with the port provided
func NewServer(port int) *Server {
return &Server{
hub: NewHub(),
srv: &http.Server{Addr: fmt.Sprintf(":%d", port)},
}
}
// Start starts the server and lets the hub listen for clients
func (s *Server) Start() {
s.startHub()
s.setupRoute()
s.startServer()
}
// Sync sends a sync message to the clients
func (s *Server) Sync() {
message := bytes.TrimSpace([]byte("sync"))
s.hub.broadcast <- message
}
// Stop stops the hub and the server gracefully
func (s *Server) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
s.hub.stop()
return s.srv.Shutdown(ctx)
}
func (s *Server) setupRoute() {
http.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) {
communicate(s.hub, w, r)
})
}
func (s *Server) startHub() {
go s.hub.listen()
}
func (s *Server) startServer() {
go s.srv.ListenAndServe()
log.Println("Serving sync server at", s.srv.Addr)
}