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) { func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options ListenerOptions) {
errChan := make(chan error, 10)
for { for {
_, message, err := p.socket.Read(context.Background()) _, message, err := p.socket.Read(context.Background())
if err != nil { if err != nil {
@ -62,17 +64,35 @@ func (p *WebSocketPeer) ListenForMessages(callback EventCallback, options Listen
break break
} }
err = callback(message) // Process each message in a separate goroutine
if err != nil { 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 { if options.OnError != nil {
(*options.OnError)(err) (*options.OnError)(err)
} }
default:
} }
} }
if options.OnClose != nil { if options.OnClose != nil {
(*options.OnClose)() (*options.OnClose)()
} }
// Handle remaining errors
close(errChan)
for err := range errChan {
if options.OnError != nil {
(*options.OnError)(err)
}
}
} }
func (p *WebSocketPeer) End() error { func (p *WebSocketPeer) End() error {