Add mutexes around websockets

We replace the bare websocket.Conn type with a new Connection type which
implements `WriteJSON`, `WriteMessage`, and `Close`.  The Connection
type adds mutexes around writes since gorilla doesn't support concurrent
writes to websockets.

Signed-off-by: Honza Pokorny <honza@pokorny.ca>
This commit is contained in:
Honza Pokorny
2022-01-12 10:54:45 -04:00
committed by fiatjaf
parent ba0507cce7
commit a3df2cb893
3 changed files with 51 additions and 20 deletions

33
connection.go Normal file
View File

@@ -0,0 +1,33 @@
package nostr
import (
"github.com/gorilla/websocket"
"sync"
)
type Connection struct {
socket *websocket.Conn
mutex sync.Mutex
}
func NewConnection(socket *websocket.Conn) *Connection {
return &Connection{
socket: socket,
}
}
func (c *Connection) WriteJSON(v interface{}) error {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.socket.WriteJSON(v)
}
func (c *Connection) WriteMessage(messageType int, data []byte) error {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.socket.WriteMessage(messageType, data)
}
func (c *Connection) Close() error {
return c.socket.Close()
}