neko/internal/websocket/peer.go

65 lines
1.2 KiB
Go
Raw Normal View History

2020-11-26 06:36:33 +13:00
package websocket
import (
"encoding/json"
"sync"
"github.com/gorilla/websocket"
"demodesk/neko/internal/types"
2021-03-26 02:08:26 +13:00
"demodesk/neko/internal/types/event"
"demodesk/neko/internal/types/message"
2021-03-30 11:37:06 +13:00
"demodesk/neko/internal/utils"
2020-11-26 06:36:33 +13:00
)
type WebSocketPeerCtx struct {
2021-02-15 05:11:21 +13:00
mu sync.Mutex
2020-11-26 06:36:33 +13:00
session types.Session
2021-02-15 05:11:21 +13:00
manager *WebSocketManagerCtx
2020-11-26 06:36:33 +13:00
connection *websocket.Conn
}
2021-02-15 05:11:21 +13:00
func (peer *WebSocketPeerCtx) Send(v interface{}) error {
peer.mu.Lock()
defer peer.mu.Unlock()
2020-11-26 06:36:33 +13:00
2021-02-15 05:11:21 +13:00
if peer.connection == nil {
2020-11-26 06:36:33 +13:00
return nil
}
raw, err := json.Marshal(v)
if err != nil {
return err
}
2021-02-15 05:11:21 +13:00
peer.manager.logger.Debug().
2021-03-14 11:27:28 +13:00
Str("session_id", peer.session.ID()).
2021-02-15 05:11:21 +13:00
Str("address", peer.connection.RemoteAddr().String()).
2020-11-26 06:36:33 +13:00
Str("raw", string(raw)).
Msg("sending message to client")
2021-02-15 05:11:21 +13:00
return peer.connection.WriteMessage(websocket.TextMessage, raw)
2020-11-26 06:36:33 +13:00
}
2021-02-15 05:11:21 +13:00
func (peer *WebSocketPeerCtx) Destroy() error {
if peer.connection == nil {
2020-11-26 06:36:33 +13:00
return nil
}
2021-03-26 02:08:26 +13:00
var errs []error
// send disconnect
err := peer.Send(
message.SystemDisconnect{
Event: event.SYSTEM_DISCONNECT,
Message: "connection destroyed",
})
errs = append(errs, err)
// close connection
err = peer.connection.Close()
errs = append(errs, err)
return utils.ErrorsJoin(errs)
2020-11-26 06:36:33 +13:00
}