/
start.go
55 lines (50 loc) · 1.35 KB
/
start.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
package replicatr
import (
"errors"
"net"
"net/http"
"strconv"
"time"
"github.com/Hubmakerlabs/replicatr/pkg/context"
"github.com/fasthttp/websocket"
"github.com/rs/cors"
)
func (rl *Relay) Router() *http.ServeMux {
return rl.serveMux
}
// Start creates an http server and starts listening on given host and port.
func (rl *Relay) Start(host string, port int, started ...chan bool) (err error) {
addr := net.JoinHostPort(host, strconv.Itoa(port))
var ln net.Listener
if ln, err = net.Listen("tcp", addr); rl.E.Chk(err) {
return
}
rl.Addr = ln.Addr().String()
rl.httpServer = &http.Server{
Handler: cors.Default().Handler(rl),
Addr: addr,
WriteTimeout: 2 * time.Second,
ReadTimeout: 2 * time.Second,
IdleTimeout: 30 * time.Second,
}
// notify caller that we're starting
for _, s := range started {
close(s)
}
if err = rl.httpServer.Serve(ln); errors.Is(err, http.ErrServerClosed) {
return nil
} else if rl.Log.E.Chk(err) {
return
}
return
}
// Shutdown sends a websocket close control message to all connected clients.
func (rl *Relay) Shutdown(c context.T) {
rl.Log.E.Chk(rl.httpServer.Shutdown(c))
rl.clients.Range(func(conn *websocket.Conn, _ struct{}) bool {
rl.E.Chk(conn.WriteControl(websocket.CloseMessage, nil, time.Now().Add(time.Second)))
rl.E.Chk(conn.Close())
rl.clients.Delete(conn)
return true
})
}