fix: prevent channel closed panic
This commit is contained in:
parent
dced32ab21
commit
13ca22d80e
14
net/ws.go
14
net/ws.go
|
@ -5,6 +5,7 @@ import (
|
||||||
"git.lumeweb.com/LumeWeb/libs5-go/encoding"
|
"git.lumeweb.com/LumeWeb/libs5-go/encoding"
|
||||||
"net/url"
|
"net/url"
|
||||||
"nhooyr.io/websocket"
|
"nhooyr.io/websocket"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -55,6 +56,8 @@ func (p *WebSocketPeer) RenderLocationURI() string {
|
||||||
|
|
||||||
func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options ListenerOptions) {
|
func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options ListenerOptions) {
|
||||||
errChan := make(chan error, 10)
|
errChan := make(chan error, 10)
|
||||||
|
doneChan := make(chan struct{})
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
for {
|
for {
|
||||||
_, message, err := p.socket.Read(context.Background())
|
_, message, err := p.socket.Read(context.Background())
|
||||||
|
@ -65,11 +68,17 @@ func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options Listen
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
wg.Add(1)
|
||||||
// Process each message in a separate goroutine
|
// Process each message in a separate goroutine
|
||||||
go func(msg []byte) {
|
go func(msg []byte) {
|
||||||
|
defer wg.Done()
|
||||||
// Call the callback and send any errors to the error channel
|
// Call the callback and send any errors to the error channel
|
||||||
if err := callback(msg); err != nil {
|
if err := callback(msg); err != nil {
|
||||||
errChan <- err
|
select {
|
||||||
|
case errChan <- err:
|
||||||
|
case <-doneChan:
|
||||||
|
// Stop sending errors if doneChan is closed
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}(message)
|
}(message)
|
||||||
|
|
||||||
|
@ -87,6 +96,9 @@ func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options Listen
|
||||||
(*options.OnClose)()
|
(*options.OnClose)()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close doneChan and wait for all goroutines to finish
|
||||||
|
close(doneChan)
|
||||||
|
wg.Wait()
|
||||||
// Handle remaining errors
|
// Handle remaining errors
|
||||||
close(errChan)
|
close(errChan)
|
||||||
for err := range errChan {
|
for err := range errChan {
|
||||||
|
|
Loading…
Reference in New Issue