Expand description
Handler traits and implementations for WebSocket message processing.
This module provides the foundation for handling WebSocket messages with a flexible, type-safe interface. Handlers can accept multiple extractors and return various response types, making it easy to build complex message processing logic.
§Overview
The handler system consists of three main components:
Handler
trait: Core trait that all handlers implementIntoResponse
trait: Converts handler return values into messagesHandlerService
: Wrapper that bridges async functions to the Handler trait
§Handler Signatures
Handlers can have various signatures with different combinations of extractors:
use wsforge::prelude::*;
use std::sync::Arc;
// No extractors
async fn simple() -> Result<String> {
Ok("Hello!".to_string())
}
// Single extractor
async fn with_message(msg: Message) -> Result<String> {
Ok("Received".to_string())
}
// Multiple extractors
async fn complex(
Json(data): Json<serde_json::Value>,
conn: Connection,
State(manager): State<Arc<ConnectionManager>>,
) -> Result<()> {
Ok(())
}
§Return Types
Handlers can return various types that implement IntoResponse
:
Return Type | Description | Example |
---|---|---|
() | No response sent | async fn handler() -> Result<()> |
String | Text message | async fn handler() -> Result<String> |
&str | Text message | async fn handler() -> Result<&str> |
Message | Raw message | async fn handler() -> Result<Message> |
Vec<u8> | Binary message | async fn handler() -> Result<Vec<u8>> |
JsonResponse<T> | JSON response | async fn handler() -> Result<JsonResponse<T>> |
Result<T> | Automatic error handling | Any of above wrapped in Result |
§Examples
§Echo Handler
use wsforge::prelude::*;
async fn echo_handler(msg: Message) -> Result<Message> {
Ok(msg)
}
§JSON Processing
use wsforge::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Request {
action: String,
}
#[derive(Serialize)]
struct Response {
status: String,
result: String,
}
async fn json_handler(Json(req): Json<Request>) -> Result<JsonResponse<Response>> {
Ok(JsonResponse(Response {
status: "success".to_string(),
result: format!("Executed: {}", req.action),
}))
}
§Broadcasting
use wsforge::prelude::*;
use std::sync::Arc;
async fn broadcast_handler(
msg: Message,
conn: Connection,
State(manager): State<Arc<ConnectionManager>>,
) -> Result<()> {
// Broadcast to everyone except sender
manager.broadcast_except(conn.id(), msg);
Ok(())
}
Structs§
- Handler
Service - Service wrapper for handler functions.
- Json
Response - JSON response wrapper.
Traits§
- Handler
- Core trait for message handlers.
- Into
Handler - Helper trait for converting functions into handlers.
- Into
Response - Trait for converting handler return values into WebSocket messages.
Functions§
- handler
- Converts an async function into a handler.