Skip to main content

ws

Attribute Macro ws 

Source
#[ws]
Expand description

Generate WebSocket JSON-RPC handlers from an impl block.

Methods are exposed as JSON-RPC methods over WebSocket connections. Supports both sync and async methods.

§Basic Usage

use server_less::ws;

#[ws(path = "/ws")]
impl ChatService {
    fn send_message(&self, room: String, content: String) -> Message {
        // ...
    }
}

§With Async Methods

#[ws(path = "/ws")]
impl ChatService {
    // Async methods work seamlessly
    async fn send_message(&self, room: String, content: String) -> Message {
        // Can await database, network calls, etc.
    }

    // Mix sync and async
    fn get_rooms(&self) -> Vec<String> {
        // Synchronous method
    }
}

§Error Handling

#[ws(path = "/ws")]
impl ChatService {
    fn send_message(&self, room: String, content: String) -> Result<Message, ChatError> {
        if room.is_empty() {
            return Err(ChatError::InvalidRoom);
        }
        Ok(Message::new(room, content))
    }
}

§Client Usage

Clients send JSON-RPC 2.0 messages over WebSocket:

// Request
{
  "jsonrpc": "2.0",
  "method": "send_message",
  "params": {"room": "general", "content": "Hello!"},
  "id": 1
}

// Response
{
  "jsonrpc": "2.0",
  "result": {"id": 123, "room": "general", "content": "Hello!"},
  "id": 1
}

§Generated Methods

  • ws_router() -> axum::Router - Router with WebSocket endpoint
  • ws_handle_message(msg) -> String - Sync message handler
  • ws_handle_message_async(msg) -> String - Async message handler
  • ws_methods() -> Vec<&'static str> - List of available methods