Module handler

Module handler 

Source
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 implement
  • IntoResponse trait: Converts handler return values into messages
  • HandlerService: 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 TypeDescriptionExample
()No response sentasync fn handler() -> Result<()>
StringText messageasync fn handler() -> Result<String>
&strText messageasync fn handler() -> Result<&str>
MessageRaw messageasync fn handler() -> Result<Message>
Vec<u8>Binary messageasync fn handler() -> Result<Vec<u8>>
JsonResponse<T>JSON responseasync fn handler() -> Result<JsonResponse<T>>
Result<T>Automatic error handlingAny 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§

HandlerService
Service wrapper for handler functions.
JsonResponse
JSON response wrapper.

Traits§

Handler
Core trait for message handlers.
IntoHandler
Helper trait for converting functions into handlers.
IntoResponse
Trait for converting handler return values into WebSocket messages.

Functions§

handler
Converts an async function into a handler.