2023-04-27 09:03:40 +08:00
|
|
|
package writer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"nhooyr.io/websocket"
|
|
|
|
"nhooyr.io/websocket/wsjson"
|
|
|
|
)
|
|
|
|
|
2023-04-27 09:45:19 +08:00
|
|
|
func BrowserConnectionWriter(browserConnectionId string, ctx context.Context, c *websocket.Conn, toBrowserChannel chan interface{}, wg *sync.WaitGroup) {
|
2023-09-30 07:05:23 +08:00
|
|
|
log := log.WithField("_routine", "BrowserConnectionWriter").WithField("browserConnectionId", browserConnectionId)
|
2023-09-07 22:54:27 +08:00
|
|
|
defer log.Debugf("finished")
|
2023-09-30 07:05:23 +08:00
|
|
|
log.Debugf("starting")
|
|
|
|
defer wg.Done()
|
2023-04-27 09:03:40 +08:00
|
|
|
|
|
|
|
RangeLoop:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
break RangeLoop
|
|
|
|
case toBrowserMessage := <-toBrowserChannel:
|
|
|
|
{
|
2023-05-10 02:37:58 +08:00
|
|
|
var toBrowserMessageAsMap = toBrowserMessage.(map[string]interface{})
|
2023-04-27 09:03:40 +08:00
|
|
|
|
|
|
|
log.Tracef("sending to browser: %v", toBrowserMessage)
|
|
|
|
err := wsjson.Write(ctx, c, toBrowserMessage)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("error on write (browser is disconnected): %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// After the error is sent to client, close its connection
|
|
|
|
// Authentication hook unauthorized this request
|
2023-05-10 02:37:58 +08:00
|
|
|
if toBrowserMessageAsMap["type"] == "connection_error" {
|
|
|
|
var payloadAsString = toBrowserMessageAsMap["payload"].(string)
|
2023-04-27 09:03:40 +08:00
|
|
|
c.Close(websocket.StatusInternalError, payloadAsString)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|