Documentation
¶
Overview ¶
Package event provides a plain WebSocket event helper built on top of the websocket middleware.
Index ¶
- Constants
- Variables
- func Broadcast(message []byte, mType ...int)
- func CloseAll(ctx context.Context, code int, reason string) error
- func Drain()
- func EmitTo(uuid string, message []byte, mType ...int) error
- func EmitToList(uuids []string, message []byte, mType ...int)
- func Fire(event string, data []byte)
- func IsDraining() bool
- func New(callback func(kws *Websocket), config ...websocket.Config) fiber.Handler
- func NewWithConfig(callback func(kws *Websocket), eventCfg Config, wsConfig ...websocket.Config) fiber.Handler
- func Off(event string)
- func On(event string, callback EventCallback)
- type Config
- type EventCallback
- type EventPayload
- type Websocket
- func (kws *Websocket) Broadcast(message []byte, except bool, mType ...int)
- func (kws *Websocket) Close()
- func (kws *Websocket) Emit(message []byte, mType ...int)
- func (kws *Websocket) EmitTo(uuid string, message []byte, mType ...int) error
- func (kws *Websocket) EmitToList(uuids []string, message []byte, mType ...int)
- func (kws *Websocket) Fire(event string, data []byte)
- func (kws *Websocket) GetAttribute(key string) interface{}
- func (kws *Websocket) GetIntAttribute(key string) int
- func (kws *Websocket) GetStringAttribute(key string) string
- func (kws *Websocket) GetUUID() string
- func (kws *Websocket) IsAlive() bool
- func (kws *Websocket) Off(event string)
- func (kws *Websocket) On(event string, callback EventCallback)
- func (kws *Websocket) SetAttribute(key string, attribute interface{})
- func (kws *Websocket) SetUUID(uuid string) error
Constants ¶
const ( // TextMessage denotes a text data message. The text message payload is // interpreted as UTF-8 encoded text data. TextMessage = 1 // BinaryMessage denotes a binary data message. BinaryMessage = 2 // CloseMessage denotes a close control message. The optional message // payload contains a numeric code and text. Use the FormatCloseMessage // function to format a close message payload. CloseMessage = 8 // PingMessage denotes a ping control frame. PingMessage = 9 // PongMessage denotes a pong control frame. PongMessage = 10 )
Source @url:https://github.com/gorilla/websocket/blob/master/conn.go#L61 The message types are defined in RFC 6455, section 11.8.
const ( // EventMessage is fired when a text or binary message is received. EventMessage = "message" // EventPing is fired when a WebSocket ping control frame is received. EventPing = "ping" // EventPong is fired when a WebSocket pong control frame is received. EventPong = "pong" // EventDisconnect is fired when the connection is closed. When the close is // caused by an error, EventError is fired as well (with the same error). EventDisconnect = "disconnect" // EventConnect is fired when the connection is initialized, immediately // after the New / NewWithConfig callback has run and before the read loop // starts. EventConnect = "connect" // EventClose is fired when the server actively closes the connection (for // example via Close or CloseAll). EventClose = "close" // EventError is fired when an error occurs, including a failed EmitTo, a // dropped outbound message, and error-driven disconnects. EventError = "error" )
Supported event list.
Variables ¶
var ( // ErrorInvalidConnection indicates that the addressed connection is no // longer available. ErrorInvalidConnection = errors.New("message cannot be delivered invalid/gone connection") // ErrorUUIDDuplication indicates that the UUID already exists in the pool. ErrorUUIDDuplication = errors.New("UUID already exists in the available connections pool") )
var ( // PongTimeout is the interval between server-originated Ping frames. // Despite its name, this helper uses Ping for liveness; the historical // name is preserved for backwards compatibility. The value must be less // than any upstream proxy or load balancer idle timeout. // // Deprecated: prefer Config.PingInterval passed to NewWithConfig. The // package-level value is read once per connection at upgrade time; // mutating it after that has no effect on running connections. PongTimeout = time.Second // RetrySendTimeout controls how long a queued message waits before retrying. RetrySendTimeout = 20 * time.Millisecond // MaxSendRetry defines the max retries for transient socket write issues. MaxSendRetry = 5 // SendQueueSize controls the per-connection outbound message queue size. SendQueueSize = 100 // ReadTimeout is deprecated and no longer used; reads block until a // message arrives or the connection is closed. // // Deprecated: ReadTimeout is a no-op. Configure Config.ReadIdleTimeout // on NewWithConfig for the actual read deadline behaviour. ReadTimeout = 10 * time.Millisecond )
Functions ¶
func CloseAll ¶
CloseAll iterates every active connection in the in-process pool and sends a close control frame with the supplied code and reason, then waits for each helper's run() loop to exit. If ctx expires first, remaining connections are force closed via Conn.Close.
The typical usage is from a Fiber shutdown hook:
app.Hooks().OnShutdown(func() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
event.Drain()
return event.CloseAll(ctx, websocket.CloseGoingAway, "server shutting down")
})
Reason is capped at 123 bytes per RFC 6455.
func Drain ¶
func Drain()
Drain marks the package as draining. New connections are not refused automatically; the upgrade gate is the caller's responsibility (a middleware that checks IsDraining and returns 503).
func EmitTo ¶
EmitTo emits a message to a connection UUID. It returns the error to the caller and, unlike the (*Websocket).EmitTo method form, does not fire EventError.
func EmitToList ¶
EmitToList emits a message to a list of connection UUIDs. Per-UUID errors are silently ignored and, unlike the (*Websocket).EmitToList method form, no EventError is fired.
func IsDraining ¶
func IsDraining() bool
IsDraining reports whether the package is in draining mode. Upgrade handlers can poll this to refuse new connections during a graceful shutdown.
func New ¶
New returns a Fiber handler that upgrades the request to WebSocket and wraps it with the event helper using default tuning. For per-instance tuning use NewWithConfig.
func NewWithConfig ¶
func NewWithConfig(callback func(kws *Websocket), eventCfg Config, wsConfig ...websocket.Config) fiber.Handler
NewWithConfig returns a Fiber handler that upgrades the request to WebSocket and wraps it with the event helper, using the supplied per-instance tuning.
func Off ¶
func Off(event string)
Off removes all process-global listeners registered for the event via On. It is the counterpart to On and does not affect per-connection listeners registered through (*Websocket).On.
func On ¶
func On(event string, callback EventCallback)
On registers a process-global listener for an event. The callback fires for that event on every connection created by New / NewWithConfig, regardless of route or Config, and stays registered until removed with Off. For listeners scoped to a single connection use the (*Websocket).On method instead.
Types ¶
type Config ¶
type Config struct {
// PingInterval is the interval between server-originated Ping frames.
// Must be less than any upstream proxy or load balancer idle timeout.
// Zero falls back to PongTimeout, then 1s.
PingInterval time.Duration
// ReadIdleTimeout bounds how long a connection may stay silent before
// it is considered dead. Zero falls back to 3 * PingInterval.
ReadIdleTimeout time.Duration
// WriteTimeout bounds a single WriteMessage or WriteControl call. Zero
// falls back to 10s.
WriteTimeout time.Duration
// MaxMessageSize bounds the largest inbound frame in bytes. Zero falls
// back to 1 MiB. To opt out, set math.MaxInt64.
MaxMessageSize int64
// SendQueueSize is the per-connection outbound buffer. Zero falls back
// to SendQueueSize package var, then 100.
SendQueueSize int
// MaxSendRetry caps retries for transient socket write issues. Zero
// falls back to MaxSendRetry package var, then 5.
MaxSendRetry int
// RetrySendTimeout is the wait between retries. Zero falls back to
// RetrySendTimeout package var, then 20ms.
RetrySendTimeout time.Duration
// RecoverHandler is called on a panic inside a user On callback. If
// nil, panics are recovered silently.
RecoverHandler func(event string, r any)
}
Config tunes a single event helper instance. Zero values fall back to the matching deprecated package-level var, which itself falls back to the historical default. Pass via NewWithConfig.
type EventCallback ¶
type EventCallback func(payload *EventPayload)
EventCallback is the listener signature invoked when an event fires.
type EventPayload ¶
type EventPayload struct {
// Kws is the connection object.
Kws *Websocket
// Name is the event name.
Name string
// SocketUUID is the unique connection UUID.
SocketUUID string
// SocketAttributes is a snapshot of connection attributes.
SocketAttributes map[string]any
// Error is populated for disconnect and error events.
Error error
// Data is used on message, custom, and error events.
Data []byte
}
EventPayload stores information about an event and its connection.
type Websocket ¶
type Websocket struct {
// Conn is the underlying Fiber websocket connection.
Conn *websocket.Conn
// UUID is the unique connection identifier.
UUID string
// Locals wraps Fiber Locals.
Locals func(key string) interface{}
// Params wraps Fiber Params.
Params func(key string, defaultValue ...string) string
// Query wraps Fiber Query.
Query func(key string, defaultValue ...string) string
// Cookies wraps Fiber Cookies.
Cookies func(key string, defaultValue ...string) string
// contains filtered or unexported fields
}
Websocket wraps a websocket.Conn with event-bus helpers.
func (*Websocket) Broadcast ¶
Broadcast emits to all active connections, skipping the originating connection (kws) when except is true. Each failed target fires EventError on kws; the package-level Broadcast does not.
func (*Websocket) Close ¶
func (kws *Websocket) Close()
Close actively closes the current connection from the server.
func (*Websocket) EmitTo ¶
EmitTo emits a message to a connection UUID. On an invalid or dead target it fires EventError on the originating connection (kws) and returns the error; the package-level EmitTo does not fire EventError.
func (*Websocket) EmitToList ¶
EmitToList emits a message to a list of connection UUIDs. Each failed UUID fires EventError on the originating connection (kws); unlike the package-level EmitToList, errors are not silently ignored.
func (*Websocket) GetAttribute ¶
GetAttribute returns an attribute from the connection.
func (*Websocket) GetIntAttribute ¶
GetIntAttribute retrieves an attribute as an int.
func (*Websocket) GetStringAttribute ¶
GetStringAttribute retrieves an attribute as a string.
func (*Websocket) Off ¶
Off removes all listeners registered for the event on this connection via the On method. It does not affect process-global listeners registered with the package-level On.
func (*Websocket) On ¶
func (kws *Websocket) On(event string, callback EventCallback)
On registers a listener for the event on this connection only. Unlike the package-level On, which is process-global, these listeners fire only for events on this connection and are discarded when it disconnects. Both per-connection and global listeners fire for a given event.
func (*Websocket) SetAttribute ¶
SetAttribute sets an attribute for the connection.