/
websocket.go
232 lines (187 loc) · 5.08 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package main
//
// Reference
//
// https://echo.labstack.com/recipes/websocket
//
//
import (
"github.com/labstack/echo"
"github.com/gorilla/websocket"
"container/list"
"time"
"encoding/json"
"net/http"
"fmt"
"github.com/labstack/echo/engine/standard"
log "github.com/Sirupsen/logrus"
)
func InitializeWebsocket(e *echo.Echo) error {
e.GET("/ws/:name", standard.WrapHandler(http.HandlerFunc(ws())))
return nil
}
var (
upgrader = websocket.Upgrader{}
)
func ws() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
// Write
err := c.WriteMessage(websocket.TextMessage, []byte("Hello, Client!"))
if err != nil {
log.Fatal(err)
}
// Read
_, msg, err := c.ReadMessage()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", msg)
}
}
}
type EventType int
const (
EVENT_JOIN = iota
EVENT_LEAVE
)
type Event struct {
Type EventType // JOIN, LEAVE
Channel string
Timestamp int
}
type Message struct {
Timestamp int
RestDescriptor RestDescriptor
}
type Subscriber struct {
Channel string
Conn *websocket.Conn
}
var (
subscribe = make(chan Subscriber, 10)
unsubscribe = make(chan string, 10)
publish = make(chan RestDescriptor, 10)
subscribers = list.New()
)
func newEvent(eventType EventType, channel string) Event {
return Event{
Type: eventType,
Channel: channel,
Timestamp: int(time.Now().Unix()),
}
}
func Join(channel string, ws *websocket.Conn) {
subscribe <- Subscriber{Channel: channel, Conn: ws}
}
func Leave(channel string) {
unsubscribe <- channel
}
func Publish(descriptor RestDescriptor) {
publish <- descriptor
}
func direct() {
for {
select {
case sub := <-subscribe:
subscribeToChannel(sub)
case message := <-publish:
sendToChannel(message)
case unsub := <-unsubscribe:
unsubscribeToChannel(unsub)
}
}
}
func cleanup() {
for {
for item := subscribers.Front(); item != nil; item = item.Next() {
sub := item.Value.(Subscriber)
if sub.Channel == "" || sub.Conn == nil {
//beego.Warn("Reaping: " + sub.Channel)
unsubscribe <- sub.Channel
}
}
time.Sleep(1 * time.Second)
}
}
func init() {
go direct()
go cleanup()
}
func subscribeToChannel(subscription Subscriber) {
if !ChannelExists(subscription.Channel) {
subscribers.PushBack(subscription)
//beego.Info("New Channel:", subscription.Channel, ";WebSocket:", subscription.Conn != nil)
} else {
//beego.Info("Old Channel:", subscription.Channel, ";WebSocket:", subscription.Conn != nil)
}
}
func unsubscribeToChannel(channel string) {
for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
if sub.Value.(Subscriber).Channel == channel {
subscribers.Remove(sub)
ws := sub.Value.(Subscriber).Conn
if ws != nil {
ws.Close()
//beego.Error("WebSocket closed:", channel)
}
break
}
}
}
func sendToChannel(descriptor RestDescriptor) {
data, err := json.Marshal(descriptor)
//beego.Info("Descriptor:", descriptor.Channel, ";Method:", descriptor.Method)
if err != nil {
//beego.Error("Fail to marshal descriptor:", err)
return
}
for item := subscribers.Front(); item != nil; item = item.Next() {
sub := item.Value.(Subscriber)
if sub.Channel == descriptor.Channel {
ws := sub.Conn
if ws != nil {
if ws.WriteMessage(websocket.TextMessage, data) != nil {
unsubscribe <- sub.Channel
}
}
}
}
}
func sendToBroadcast(descriptor RestDescriptor) {
data, err := json.Marshal(descriptor)
//beego.Info("Descriptor:", descriptor.Channel, ";Method:", descriptor.Method)
if err != nil {
//beego.Error("Fail to marshal descriptor:", err)
return
}
for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
ws := sub.Value.(Subscriber).Conn
if ws != nil {
if ws.WriteMessage(websocket.TextMessage, data) != nil {
unsubscribe <- sub.Value.(Subscriber).Channel
}
}
}
}
func ChannelExists(channel string) bool {
for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
if sub.Value.(Subscriber).Channel == channel {
return true
}
}
return false
}
func ChannelList() []string {
channels := make([]string, 0)
for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
channels = append(channels, sub.Value.(Subscriber).Channel)
}
return channels
}