websocket_handler

Attribute Macro websocket_handler 

Source
#[websocket_handler]
Expand description

Transforms an async function into a WebSocket handler.

This attribute macro wraps your async function to make it compatible with the WsForge handler system. It preserves all function attributes, visibility, and signature while adding the necessary wrapper code.

§Behavior

The macro:

  • Preserves the original function signature
  • Maintains async/await semantics
  • Keeps visibility modifiers (pub, pub(crate), etc.)
  • Preserves all other attributes
  • Does not modify the function body

§Usage

use wsforge_macros::websocket_handler;
use wsforge_core::prelude::*;

#[websocket_handler]
async fn my_handler(msg: Message) -> Result<String> {
    Ok(format!("Received: {:?}", msg))
}

§With Multiple Parameters

use wsforge_macros::websocket_handler;
use wsforge_core::prelude::*;
use std::sync::Arc;

#[websocket_handler]
async fn complex_handler(
    msg: Message,
    conn: Connection,
    State(manager): State<Arc<ConnectionManager>>,
) -> Result<()> {
    manager.broadcast(msg);
    Ok(())
}

§With Custom Return Types

use wsforge_macros::websocket_handler;
use wsforge_core::prelude::*;
use serde::Serialize;

#[derive(Serialize)]
struct Response {
    status: String,
}

#[websocket_handler]
async fn json_handler() -> Result<JsonResponse<Response>> {
    Ok(JsonResponse(Response {
        status: "ok".to_string(),
    }))
}

§Note

The function must be async and return a type that implements IntoResponse.