2020-01-25 04:47:37 +13:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
2020-02-13 17:45:29 +13:00
|
|
|
"encoding/json"
|
2020-01-25 04:47:37 +13:00
|
|
|
"strings"
|
2020-02-04 03:46:00 +13:00
|
|
|
"sync"
|
2020-01-25 04:47:37 +13:00
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type WebSocket struct {
|
|
|
|
id string
|
2020-02-14 16:52:14 +13:00
|
|
|
ws *WebSocketHandler
|
2020-01-25 04:47:37 +13:00
|
|
|
connection *websocket.Conn
|
2020-02-04 03:46:00 +13:00
|
|
|
mu sync.Mutex
|
2020-01-25 04:47:37 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
func (socket *WebSocket) Address() *string {
|
|
|
|
remote := socket.connection.RemoteAddr()
|
|
|
|
address := strings.SplitN(remote.String(), ":", -1)
|
|
|
|
if len(address[0]) < 1 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return &address[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (socket *WebSocket) Send(v interface{}) error {
|
2020-02-04 03:46:00 +13:00
|
|
|
socket.mu.Lock()
|
|
|
|
defer socket.mu.Unlock()
|
2020-01-25 04:47:37 +13:00
|
|
|
if socket.connection == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-13 17:45:29 +13:00
|
|
|
raw, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
socket.ws.logger.Debug().
|
|
|
|
Str("session", socket.id).
|
|
|
|
Str("address", socket.connection.RemoteAddr().String()).
|
|
|
|
Str("raw", string(raw)).
|
|
|
|
Msg("sending message to client")
|
|
|
|
|
|
|
|
return socket.connection.WriteMessage(websocket.TextMessage, raw)
|
2020-01-25 04:47:37 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
func (socket *WebSocket) Destroy() error {
|
|
|
|
if socket.connection == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return socket.connection.Close()
|
|
|
|
}
|