websocket.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package event
  2. import (
  3. "context"
  4. "github.com/uozi-tech/cosy/logger"
  5. )
  6. // WebSocketHubManager manages WebSocket hub initialization and context handling
  7. type WebSocketHubManager struct {
  8. ctx context.Context
  9. cancel context.CancelFunc
  10. }
  11. var (
  12. wsHubManager *WebSocketHubManager
  13. )
  14. // InitWebSocketHub initializes the WebSocket hub with proper context handling
  15. func InitWebSocketHub(ctx context.Context) {
  16. logger.Info("Initializing WebSocket hub...")
  17. hubCtx, cancel := context.WithCancel(ctx)
  18. wsHubManager = &WebSocketHubManager{
  19. ctx: hubCtx,
  20. cancel: cancel,
  21. }
  22. logger.Info("WebSocket hub initialized successfully")
  23. // Wait for context cancellation
  24. go func() {
  25. <-hubCtx.Done()
  26. logger.Info("WebSocket hub context cancelled")
  27. }()
  28. }
  29. // GetWebSocketContext returns the WebSocket hub context
  30. func GetWebSocketContext() context.Context {
  31. if wsHubManager == nil {
  32. return context.Background()
  33. }
  34. return wsHubManager.ctx
  35. }
  36. // ShutdownWebSocketHub gracefully shuts down the WebSocket hub
  37. func ShutdownWebSocketHub() {
  38. if wsHubManager != nil {
  39. wsHubManager.cancel()
  40. logger.Info("WebSocket hub shutdown completed")
  41. }
  42. }