Expand description
§Programmable WebSocket Handlers
This module provides a flexible handler API for scripting WebSocket event flows. Unlike static replay, handlers allow you to write custom logic for responding to WebSocket events, manage rooms, and route messages dynamically.
§Features
- Connection Lifecycle:
on_connectandon_disconnecthooks - Pattern Matching: Route messages with regex or JSONPath patterns
- Room Management: Broadcast messages to groups of connections
- Passthrough: Selectively forward messages to upstream servers
- Hot Reload: Automatically reload handlers when code changes (via
MOCKFORGE_WS_HOTRELOAD)
§Quick Start
use mockforge_ws::handlers::{WsHandler, WsContext, WsMessage, HandlerResult};
use async_trait::async_trait;
struct EchoHandler;
#[async_trait]
impl WsHandler for EchoHandler {
async fn on_connect(&self, ctx: &mut WsContext) -> HandlerResult<()> {
ctx.send_text("Welcome to the echo server!").await?;
Ok(())
}
async fn on_message(&self, ctx: &mut WsContext, msg: WsMessage) -> HandlerResult<()> {
if let WsMessage::Text(text) = msg {
ctx.send_text(&format!("echo: {}", text)).await?;
}
Ok(())
}
}§Message Pattern Matching
use mockforge_ws::handlers::{WsHandler, WsContext, WsMessage, HandlerResult, MessagePattern};
use async_trait::async_trait;
struct ChatHandler;
#[async_trait]
impl WsHandler for ChatHandler {
async fn on_message(&self, ctx: &mut WsContext, msg: WsMessage) -> HandlerResult<()> {
if let WsMessage::Text(text) = msg {
// Use pattern matching to route messages
if let Ok(pattern) = MessagePattern::regex(r"^/join (.+)$") {
if pattern.matches(&text) {
// Extract room name and join
if let Some(room) = text.strip_prefix("/join ") {
ctx.join_room(room).await?;
ctx.send_text(&format!("Joined room: {}", room)).await?;
}
}
}
// Handle JSON chat messages
let jsonpath_pattern = MessagePattern::jsonpath("$.type");
if jsonpath_pattern.matches(&text) {
ctx.broadcast_to_room("general", &text).await?;
}
}
Ok(())
}
}Structs§
- Handler
Registry - Handler registry for managing multiple handlers
- Message
Router - Pattern-based message router
- Passthrough
Config - Passthrough handler configuration for forwarding messages to upstream servers
- Passthrough
Handler - Passthrough handler that forwards messages to an upstream server
- Room
Manager - Room manager for broadcasting messages to groups of connections
- WsContext
- Context provided to handlers for each connection
Enums§
- Handler
Error - Error type for handler operations
- Message
Pattern - Pattern for matching WebSocket messages
- WsMessage
- WebSocket message wrapper for different message types
Traits§
- WsHandler
- Trait for WebSocket message handlers
Type Aliases§
- Connection
Id - Connection ID type
- Handler
Result - Result type for handler operations