WebSocket
Ginject has first-class WebSocket support. Learn WS controllers, WSContext, per-message contexts, subscribed events, and goroutine safety.
WebSocket
Ginject provides native WebSocket support through controllers that embed common.WS. The framework manages connection lifecycles, per-message SLA timeouts, and goroutine safety.
WS Controller Basics
Replace common.REST with common.WS and write handler methods whose names map to WebSocket event names:
WSContext
WSContext carries the WebSocket connection state for a single connection's lifetime.
Accessing the Execution Context
Per-Message Context
Each message can derive a short-lived child context with a SLA timeout:
NewMessageContext calls ctx.WithTimeout(ws.Exec(), d) internally, so cancellation propagates from connection → message → any GoSafe goroutines.
WSPayload
WSPayload is the deserialized payload from the incoming WebSocket message:
The incoming message format is JSON:
WSMessage
The full incoming message structure:
Access via ws.Message:
Subscribed Events
Clients declare which events they want to receive via a query parameter:
The * wildcard event means "all events". If events is not provided, the client receives all events.
Subprotocols
WebSocket subprotocols are supported. Set the subprotocol via the Sec-WebSocket-Protocol header:
Controllers can scope handlers to a specific subprotocol. The framework matches the client's requested subprotocol against the handler's configured subprotocol.
Sending Messages
Use the websocket.Message.Send helper:
Goroutine Safety in WS Handlers
Always use ctx.GoSafe for async work in WS handlers:
Connection Lifecycle
The framework:
- Creates a
WSContextwith its owncontext.Background()-rooted execution context. - Calls
defer cancel()on connection close, cancelling all derived per-message contexts andGoSafegoroutines. - Dispatches each incoming message to the matching handler based on the
eventfield.
Do not derive WS execution context from the HTTP upgrade request context — it is cancelled immediately after the handshake.
WS Module Registration
Register in the app module just like REST modules.