-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
65 lines (55 loc) · 1.49 KB
/
websocket.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
package events
import (
"fmt"
"net/http"
"time"
"github.com/gorilla/websocket"
)
// NewWebsocketServer will create a new websocket notifier returning the server
// that will serve the websockets, and an EventBus to send events to
func NewWebsocketServer(port string) *http.Server {
mgr := &wsManager{}
return &http.Server{
Addr: port,
Handler: mgr,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
}
type wsManager struct {
conns []*websocket.Conn
}
func (mgr *wsManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
rootHandler(w, r)
case "/events":
mgr.webSocketHandler(w, r)
default:
http.NotFoundHandler().ServeHTTP(w, r)
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", indexHTML)
}
func (mgr *wsManager) webSocketHandler(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Origin") != "http://"+r.Host {
http.Error(w, "Origin not allowed", 403)
return
}
conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
if err != nil {
http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
}
mgr.conns = append(mgr.conns, conn)
}
// handleEvent will handle the event passed to it by writing it out
// to all the connections. It is an EventBus function
func (mgr *wsManager) handleEvent(evt Event) {
for _, conn := range mgr.conns {
if err := conn.WriteJSON(evt); err != nil {
fmt.Println(err)
}
}
}