mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-25 10:18:59 +02:00
refactor(websocket): enhance connection management by ensuring resources are released on context cancellation
This commit is contained in:
@@ -31,6 +31,7 @@ type Manager struct {
|
|||||||
err error
|
err error
|
||||||
|
|
||||||
writeLock sync.Mutex
|
writeLock sync.Mutex
|
||||||
|
closeOnce sync.Once
|
||||||
}
|
}
|
||||||
|
|
||||||
var defaultUpgrader = websocket.Upgrader{
|
var defaultUpgrader = websocket.Upgrader{
|
||||||
@@ -111,6 +112,12 @@ func NewManagerWithUpgrade(c *gin.Context) (*Manager, error) {
|
|||||||
go cm.pingCheckRoutine()
|
go cm.pingCheckRoutine()
|
||||||
go cm.readRoutine()
|
go cm.readRoutine()
|
||||||
|
|
||||||
|
// Ensure resources are released when parent context is canceled.
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
cm.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
return cm, nil
|
return cm, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -209,6 +216,10 @@ func (cm *Manager) ReadJSON(out any, timeout time.Duration) error {
|
|||||||
|
|
||||||
// Close closes the connection and cancels the context
|
// Close closes the connection and cancels the context
|
||||||
func (cm *Manager) Close() {
|
func (cm *Manager) Close() {
|
||||||
|
cm.closeOnce.Do(cm.close)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cm *Manager) close() {
|
||||||
cm.cancel()
|
cm.cancel()
|
||||||
|
|
||||||
cm.writeLock.Lock()
|
cm.writeLock.Lock()
|
||||||
|
|||||||
Reference in New Issue
Block a user