refactor: send every message in a coroutine and manage errors in a dedicated channel

This commit is contained in:
Derrick Hammer 2024-01-08 12:08:15 -05:00
parent e011d452d5
commit 1fe2940fc4
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 22 additions and 2 deletions

View File

@ -53,6 +53,8 @@ func (p *WebSocketPeer) RenderLocationURI() string {
}
func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options ListenerOptions) {
errChan := make(chan error, 10)
for {
_, message, err := p.socket.Read(context.Background())
if err != nil {
@ -62,17 +64,35 @@ func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options Listen
break
}
err = callback(message)
if err != nil {
// Process each message in a separate goroutine
go func(msg []byte) {
// Call the callback and send any errors to the error channel
if err := callback(msg); err != nil {
errChan <- err
}
}(message)
// Non-blocking error check
select {
case err := <-errChan:
if options.OnError != nil {
(*options.OnError)(err)
}
default:
}
}
if options.OnClose != nil {
(*options.OnClose)()
}
// Handle remaining errors
close(errChan)
for err := range errChan {
if options.OnError != nil {
(*options.OnError)(err)
}
}
}
func (p *WebSocketPeer) End() error {