From 2b866fdcb4a69285306a4db7910742b5525bc79f Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Thu, 25 Jul 2019 19:30:37 +0100 Subject: [PATCH] Serialise websocket writes as per https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency --- client.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/client.go b/client.go index 22af1f2..94a1aa0 100644 --- a/client.go +++ b/client.go @@ -9,6 +9,7 @@ import ( "net/url" "os" "os/signal" + "sync" "time" "github.com/gorilla/websocket" @@ -26,12 +27,13 @@ func Log() *log.Logger { type EventHandler func(ctx context.Context, client *Client, event Event) error type Client struct { - ctx context.Context - params RegistrationParams - c *websocket.Conn - actions map[string]*Action - handlers map[string][]EventHandler - done chan struct{} + ctx context.Context + params RegistrationParams + c *websocket.Conn + actions map[string]*Action + handlers map[string][]EventHandler + done chan struct{} + sendMutex sync.Mutex } func NewClient(ctx context.Context, params RegistrationParams) *Client { @@ -140,6 +142,8 @@ func (client *Client) register(params RegistrationParams) error { func (client *Client) send(event Event) error { j, _ := json.Marshal(event) + client.sendMutex.Lock() + defer client.sendMutex.Unlock() logger.Printf("sending message: %v\n", string(j)) return client.c.WriteJSON(event) }