Skip to content

Commit

Permalink
Ignoring errors if connection is closed from our side
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Nov 8, 2023
1 parent 43be50a commit 1efdfa8
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion pkg/ws/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"strings"
"sync"
"sync/atomic"

"github.com/fatih/color"
"golang.org/x/net/websocket"
Expand Down Expand Up @@ -44,6 +45,7 @@ type Connection struct {
ws *websocket.Conn
Messages chan Message
waitGroup *sync.WaitGroup
isClosed atomic.Bool
}

type Options struct {
Expand Down Expand Up @@ -92,6 +94,8 @@ func NewWS(url string, opts Options) (*Connection, error) {

messages := make(chan Message, WSMessageBufferSize)

wsInsp := &Connection{ws: ws, Messages: messages, waitGroup: &waitGroup}

go func() {
defer func() {
waitGroup.Wait()
Expand All @@ -103,6 +107,10 @@ func NewWS(url string, opts Options) (*Connection, error) {

err = websocket.Message.Receive(ws, &msg)
if err != nil {
if wsInsp.isClosed.Load() {
return
}

if err.Error() == "EOF" {
color.New(color.FgRed).Println("Connection closed by the server")
} else {
Expand All @@ -116,7 +124,7 @@ func NewWS(url string, opts Options) (*Connection, error) {
}
}()

return &Connection{ws: ws, Messages: messages, waitGroup: &waitGroup}, nil
return wsInsp, nil
}

func (wsInsp *Connection) Send(msg string) (*Message, error) {
Expand All @@ -133,5 +141,11 @@ func (wsInsp *Connection) Send(msg string) (*Message, error) {
}

func (wsInsp *Connection) Close() {
if wsInsp.isClosed.Load() {
return
}

wsInsp.isClosed.Store(true)

wsInsp.ws.Close()
}

0 comments on commit 1efdfa8

Please sign in to comment.