Skip to content

Commit 930ff6b

Browse files
committed
fix: websocket keepalive goroutine leak
1 parent 18eb162 commit 930ff6b

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

v2/websocket.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ var wsServe = func(cfg *WsConfig, handler WsHandler, errHandler ErrHandler) (don
5858
if WebsocketKeepalive {
5959
// This function overwrites the default ping frame handler
6060
// sent by the websocket API server
61-
keepAlive(c, WebsocketTimeout)
61+
keepAlive(doneC, c, WebsocketTimeout)
6262
}
6363

6464
// Wait for the stopC channel to be closed. We do that in a
@@ -87,9 +87,7 @@ var wsServe = func(cfg *WsConfig, handler WsHandler, errHandler ErrHandler) (don
8787
return
8888
}
8989

90-
func keepAlive(c *websocket.Conn, timeout time.Duration) {
91-
ticker := time.NewTicker(timeout)
92-
90+
func keepAlive(done chan struct{}, c *websocket.Conn, timeout time.Duration) {
9391
lastResponse := time.Now()
9492

9593
c.SetPingHandler(func(pingData string) error {
@@ -109,12 +107,18 @@ func keepAlive(c *websocket.Conn, timeout time.Duration) {
109107
})
110108

111109
go func() {
110+
ticker := time.NewTicker(timeout)
112111
defer ticker.Stop()
112+
113113
for {
114-
<-ticker.C
115-
if time.Since(lastResponse) > timeout {
116-
c.Close()
114+
select {
115+
case <-done:
117116
return
117+
case <-ticker.C:
118+
if time.Since(lastResponse) > timeout {
119+
c.Close()
120+
return
121+
}
118122
}
119123
}
120124
}()

0 commit comments

Comments
 (0)