mirror of
https://github.com/Luzifer/twitch-manager.git
synced 2024-12-21 04:11:17 +00:00
Fix concurrent writes to socket
This commit is contained in:
parent
c3344534a8
commit
dce43ffd99
1 changed files with 18 additions and 2 deletions
20
api.go
20
api.go
|
@ -93,25 +93,41 @@ func handleUpdateSocket(w http.ResponseWriter, r *http.Request) {
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
|
|
||||||
// Register listener
|
// Register listener
|
||||||
id := uuid.Must(uuid.NewV4()).String()
|
var (
|
||||||
subscribeSocket(id, conn.WriteJSON)
|
connLock = new(sync.Mutex)
|
||||||
|
id = uuid.Must(uuid.NewV4()).String()
|
||||||
|
)
|
||||||
|
subscribeSocket(id, func(msg interface{}) error {
|
||||||
|
connLock.Lock()
|
||||||
|
defer connLock.Unlock()
|
||||||
|
|
||||||
|
return conn.WriteJSON(msg)
|
||||||
|
})
|
||||||
defer unsubscribeSocket(id)
|
defer unsubscribeSocket(id)
|
||||||
|
|
||||||
keepAlive := time.NewTicker(5 * time.Second)
|
keepAlive := time.NewTicker(5 * time.Second)
|
||||||
defer keepAlive.Stop()
|
defer keepAlive.Stop()
|
||||||
go func() {
|
go func() {
|
||||||
for range keepAlive.C {
|
for range keepAlive.C {
|
||||||
|
connLock.Lock()
|
||||||
|
|
||||||
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||||
log.WithError(err).Error("Unable to send ping message")
|
log.WithError(err).Error("Unable to send ping message")
|
||||||
|
connLock.Unlock()
|
||||||
conn.Close()
|
conn.Close()
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
connLock.Unlock()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
connLock.Lock()
|
||||||
if err := conn.WriteJSON(compileSocketMessage(msgTypeStore, store)); err != nil {
|
if err := conn.WriteJSON(compileSocketMessage(msgTypeStore, store)); err != nil {
|
||||||
log.WithError(err).Error("Unable to send initial state")
|
log.WithError(err).Error("Unable to send initial state")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
connLock.Unlock()
|
||||||
|
|
||||||
// Handle socket
|
// Handle socket
|
||||||
for {
|
for {
|
||||||
|
|
Loading…
Reference in a new issue