websocket peer add event.

This commit is contained in:
Miroslav Šedivý 2021-09-01 21:11:07 +02:00
parent 4341257f14
commit 5b5e541cc0
3 changed files with 22 additions and 17 deletions

View File

@ -15,7 +15,7 @@ type WebSocketHandler func(Session, WebSocketMessage) bool
type CheckOrigin func(r *http.Request) bool
type WebSocketPeer interface {
Send(v interface{}) error
Send(event string, payload interface{})
Destroy()
}

View File

@ -307,13 +307,10 @@ func (manager *WebSocketManagerCtx) handle(connection *websocket.Conn, session t
case raw := <-bytes:
data := types.WebSocketMessage{}
if err := json.Unmarshal(raw, &data); err != nil {
logger.Error().Err(err).Msg("message parsing has failed")
logger.Error().Err(err).Msg("message unmarshalling has failed")
break
}
// TODO: Switch to payload based messages.
data.Payload = raw
logger.Debug().
Str("address", connection.RemoteAddr().String()).
Str("event", data.Event).

View File

@ -19,25 +19,35 @@ type WebSocketPeerCtx struct {
connection *websocket.Conn
}
func (peer *WebSocketPeerCtx) Send(v interface{}) error {
func (peer *WebSocketPeerCtx) Send(event string, payload interface{}) {
peer.mu.Lock()
defer peer.mu.Unlock()
if peer.connection == nil {
return nil
return
}
raw, err := json.Marshal(v)
raw, err := json.Marshal(payload)
if err != nil {
return err
peer.logger.Error().Err(err).Str("event", event).Msg("message marshalling has failed")
return
}
err = peer.connection.WriteJSON(types.WebSocketMessage{
Event: event,
Payload: raw,
})
if err != nil {
peer.logger.Error().Err(err).Str("event", event).Msg("send message error")
return
}
peer.logger.Debug().
Str("address", peer.connection.RemoteAddr().String()).
Str("raw", string(raw)).
Str("event", event).
Str("payload", string(raw)).
Msg("sending message to client")
return peer.connection.WriteMessage(websocket.TextMessage, raw)
}
func (peer *WebSocketPeerCtx) Destroy() {
@ -48,13 +58,11 @@ func (peer *WebSocketPeerCtx) Destroy() {
return
}
if err := peer.Send(
peer.Send(
event.SYSTEM_DISCONNECT,
message.SystemDisconnect{
Event: event.SYSTEM_DISCONNECT,
Message: "connection destroyed",
}); err != nil {
peer.logger.Warn().Err(err).Msg("failed to send disconnect event")
}
})
if err := peer.connection.Close(); err != nil {
peer.logger.Warn().Err(err).Msg("peer connection destroyed with an error")