neko/server/internal/websocket/socket.go

56 lines
1.0 KiB
Go
Raw Normal View History

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-04-05 15:49:43 +12:00
address string
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
}
2020-04-05 15:49:43 +12:00
func (socket *WebSocket) Address() string {
//remote := socket.connection.RemoteAddr()
address := strings.SplitN(socket.address, ":", -1)
2020-01-25 04:47:37 +13:00
if len(address[0]) < 1 {
2020-04-05 15:49:43 +12:00
return socket.address
2020-01-25 04:47:37 +13:00
}
2020-04-05 15:49:43 +12:00
return address[0]
2020-01-25 04:47:37 +13:00
}
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()
}