-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsconn_service.go
143 lines (131 loc) · 4.43 KB
/
wsconn_service.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
package wsconn
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/sivaosorg/govm/entity"
"github.com/sivaosorg/govm/wsconnx"
)
type WebsocketService interface {
Run(topic string)
WriteMessage(conn *websocket.Conn, message wsconnx.WsConnMessagePayload) error
CloseSubscriber(conn *websocket.Conn)
AddSubscriber(conn *websocket.Conn, subscription wsconnx.WsConnSubscription)
SubscribeMessage(c *gin.Context)
BroadcastMessage(message wsconnx.WsConnMessagePayload)
RegisterTopic(c *gin.Context)
}
type websocketServiceImpl struct {
wsConf *Websocket
}
func NewWebsocketService(wsConf *Websocket) WebsocketService {
s := &websocketServiceImpl{
wsConf: wsConf,
}
return s
}
func (ws *websocketServiceImpl) Run(topic string) {
channel, ok := ws.wsConf.broadcast[topic]
if !ok {
_logger.Warn("Topic not found: %v", topic)
return
}
for {
message := <-channel
ws.wsConf.mutex.Lock()
for subscriber, subscription := range ws.wsConf.subscribers {
if subscription.Topic == topic {
err := ws.WriteMessage(subscriber, message)
if err != nil {
_logger.Error("An error occurred while writing message", err)
ws.CloseSubscriber(subscriber)
}
}
}
ws.wsConf.mutex.Unlock()
}
}
func (ws *websocketServiceImpl) WriteMessage(conn *websocket.Conn, message wsconnx.WsConnMessagePayload) error {
message.SetGenesisTimestamp(time.Now())
conn.SetWriteDeadline(time.Now().Add(ws.wsConf.Option.WriteWait))
return conn.WriteJSON(message)
}
func (ws *websocketServiceImpl) CloseSubscriber(conn *websocket.Conn) {
conn.Close()
delete(ws.wsConf.subscribers, conn)
}
func (ws *websocketServiceImpl) AddSubscriber(conn *websocket.Conn, subscription wsconnx.WsConnSubscription) {
ws.wsConf.mutex.Lock()
defer ws.wsConf.mutex.Unlock()
if conn != nil {
ws.wsConf.subscribers[conn] = subscription
if _, ok := ws.wsConf.broadcast[subscription.Topic]; !ok {
ws.wsConf.broadcast[subscription.Topic] = make(chan wsconnx.WsConnMessagePayload)
go ws.Run(subscription.Topic)
}
}
}
// Parse user ID and desired topic from the WebSocket message
// Read incoming messages, but ignore them as we handle sending only
func (ws *websocketServiceImpl) SubscribeMessage(c *gin.Context) {
conn, err := ws.wsConf.upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
_logger.Error("An error occurred while upgrading connection", err)
return
}
defer ws.CloseSubscriber(conn)
var subscription wsconnx.WsConnSubscription
if err := conn.ReadJSON(&subscription); err != nil {
_logger.Error("An error occurred while reading subscription", err)
return
}
ws.AddSubscriber(conn, subscription)
if ws.wsConf.IsEnabledClosure {
conn.SetReadLimit(int64(ws.wsConf.Option.MaxMessageSize))
conn.SetReadDeadline(time.Now().Add(ws.wsConf.Option.PongWait))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(ws.wsConf.Option.PongWait))
return nil
})
}
for {
if _, _, err := conn.ReadMessage(); err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
_logger.Error("An error occurred while reading message", err)
}
break
}
}
}
// Find the channel for the specific topic and send the message to it
func (ws *websocketServiceImpl) BroadcastMessage(message wsconnx.WsConnMessagePayload) {
ws.wsConf.mutex.Lock()
defer ws.wsConf.mutex.Unlock()
if channel, ok := ws.wsConf.broadcast[message.Topic]; ok {
channel <- message
}
}
func (ws *websocketServiceImpl) RegisterTopic(c *gin.Context) {
ws.wsConf.mutex.Lock()
defer ws.wsConf.mutex.Unlock()
response := entity.NewResponseEntity()
var subscription wsconnx.WsConnSubscription
if err := c.ShouldBindJSON(&subscription); err != nil {
response.SetStatusCode(http.StatusBadRequest).SetError(err).SetMessage(err.Error())
c.JSON(response.StatusCode, response)
return
}
if _, ok := ws.wsConf.Topics[subscription.Topic]; ok {
response.SetStatusCode(http.StatusOK).SetMessage(fmt.Sprintf("Topic %s already registered", subscription.Topic)).SetData(subscription)
c.JSON(response.StatusCode, response)
return
}
ws.wsConf.Topics[subscription.Topic] = true
ws.wsConf.broadcast[subscription.Topic] = make(chan wsconnx.WsConnMessagePayload)
go ws.Run(subscription.Topic)
response.SetStatusCode(http.StatusOK).SetMessage(fmt.Sprintf("Topic %s registered successfully", subscription.Topic)).SetData(subscription)
c.JSON(response.StatusCode, response)
return
}