Skip to content

Commit e2f4648

Browse files
committed
fix: use a context to stop the keepalive goroutine
1 parent 30359ab commit e2f4648

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

v2/common/websocket/client.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -337,14 +337,17 @@ func NewConnection(
337337
return nil, err
338338
}
339339

340+
ctx, cancel := context.WithCancel(context.Background())
341+
340342
wsConn := &connection{
341343
conn: underlyingWsConn,
342344
connectionMu: sync.Mutex{},
343345
lastResponseMu: sync.Mutex{},
344346
initUnderlyingWsConnFn: initUnderlyingWsConnFn,
345347
keepaliveTimeout: keepaliveTimeout,
346348
isKeepAliveNeeded: isKeepAliveNeeded,
347-
done: make(chan struct{}),
349+
ctx: ctx,
350+
cancel: cancel,
348351
}
349352

350353
if isKeepAliveNeeded {
@@ -363,7 +366,8 @@ type connection struct {
363366
initUnderlyingWsConnFn func() (*websocket.Conn, error)
364367
keepaliveTimeout time.Duration
365368
isKeepAliveNeeded bool
366-
done chan struct{}
369+
ctx context.Context
370+
cancel context.CancelFunc
367371
}
368372

369373
type Connection interface {
@@ -383,7 +387,7 @@ func (c *connection) WriteMessage(messageType int, data []byte) error {
383387
func (c *connection) ReadMessage() (int, []byte, error) {
384388
msgType, msg, err := c.conn.ReadMessage()
385389
if err != nil {
386-
close(c.done)
390+
c.cancel()
387391
}
388392
return msgType, msg, err
389393
}
@@ -408,7 +412,7 @@ func (c *connection) keepAlive(timeout time.Duration) {
408412

409413
for {
410414
select {
411-
case <-c.done:
415+
case <-c.ctx.Done():
412416
return
413417
case <-ticker.C:
414418
err := c.ping()

0 commit comments

Comments
 (0)