Module router

Module router 

Source
Expand description

Routing and server management for WebSocket connections.

This module provides the core routing infrastructure for WsForge, allowing you to define handlers for different message patterns, manage application state, and configure server behavior. The router handles both WebSocket connections and static file serving on the same port.

§Overview

The Router is the main entry point for building a WebSocket server. It provides a builder-style API for:

  • Registering message handlers for specific routes
  • Managing shared application state
  • Serving static files (HTML, CSS, JS)
  • Configuring connection lifecycle callbacks
  • Managing WebSocket connections

§Architecture

┌─────────────────┐
│  TCP Listener   │
└────────┬────────┘
         │
         ├──→ HTTP Request → Static File Handler
         │
         └──→ WebSocket Upgrade → Connection Manager
                                   │
                                   ├──→ on_connect callback
                                   │
                                   ├──→ Message Router → Handler
                                   │
                                   └──→ on_disconnect callback

§Examples

§Simple Echo Server

use wsforge::prelude::*;

async fn echo(msg: Message) -> Result<Message> {
    Ok(msg)
}

let router = Router::new()
    .default_handler(handler(echo));

router.listen("127.0.0.1:8080").await?;

§Multiple Routes

use wsforge::prelude::*;

async fn echo(msg: Message) -> Result<Message> {
    Ok(msg)
}

async fn stats(State(manager): State<Arc<ConnectionManager>>) -> Result<String> {
    Ok(format!("Active connections: {}", manager.count()))
}

let router = Router::new()
    .route("/echo", handler(echo))
    .route("/stats", handler(stats))
    .default_handler(handler(echo));

router.listen("127.0.0.1:8080").await?;

§With State and Callbacks

use wsforge::prelude::*;
use std::sync::Arc;

async fn broadcast(msg: Message, State(manager): State<Arc<ConnectionManager>>) -> Result<()> {
    manager.broadcast(msg);
    Ok(())
}

let router = Router::new()
    .default_handler(handler(broadcast))
    .on_connect(|manager, conn_id| {
        println!("✅ User {} connected (Total: {})", conn_id, manager.count());
    })
    .on_disconnect(|manager, conn_id| {
        println!("❌ User {} disconnected", conn_id);
    });

router.listen("127.0.0.1:8080").await?;

§Hybrid HTTP/WebSocket Server

use wsforge::prelude::*;

async fn ws_handler(msg: Message) -> Result<Message> {
    Ok(msg)
}

let router = Router::new()
    .serve_static("public")  // Serve HTML/CSS/JS from 'public' folder
    .default_handler(handler(ws_handler));

// Handles both HTTP (for files) and WebSocket on same port
router.listen("127.0.0.1:8080").await?;

Structs§

Route
Represents a single route with its path and handler.
Router
The main router for WebSocket servers.