neko/server/internal/websocket/socket.go

42 lines
699 B
Go
Raw Normal View History

2020-01-25 04:47:37 +13:00
package websocket
import (
"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
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
}
return socket.connection.WriteJSON(v)
}
func (socket *WebSocket) Destroy() error {
if socket.connection == nil {
return nil
}
return socket.connection.Close()
}