-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
82 lines (65 loc) · 1.73 KB
/
handler.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package main
import (
//
"log"
"net/http"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func handler(w http.ResponseWriter, r *http.Request) {
var session *Session
reqid := uuid.New().String()
log.Printf("[%s] client connected\n", reqid)
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
upgradefail(w, err)
return
}
defer func() {
log.Printf("[%s] client disconnected\n", reqid)
_ = c.Close()
if session == nil {
return
}
if session.subscriber != nil {
session.subscriber.Disconnect(session.channel)
}
}()
for {
if session == nil {
session, err = authenticate(c, reqid)
if err != nil {
badrequest(c, reqid, err)
return
}
}
msg, ok := <-session.channel
if !ok {
log.Printf("[%s] event channel closed: %s\n", reqid, *session.Stream)
return
}
log.Printf("[%s] sending message to: %s\n", reqid, *session.Stream)
err := c.WriteMessage(websocket.TextMessage, msg.Data)
if err != nil {
badrequest(c, reqid, err)
return
}
}
}
func upgradefail(w http.ResponseWriter, err error) {
log.Println("Unable to upgrade to websocket connection:", err.Error())
http.Error(w, "Unable to upgrade to websocket connection", http.StatusBadRequest)
}
func badrequest(c *websocket.Conn, reqid string, err error) {
log.Printf("[%s] bad request: %s\n", reqid, err.Error())
_ = c.WriteMessage(websocket.CloseUnsupportedData, []byte(`{"error": "bad request"}`))
_ = c.Close()
}