help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
rust-web-server
/
src
RSK World
rust-web-server
Rust Web Server - High-Performance Async Web Server + WebSocket Support + JWT Authentication + File Upload + Memory Safety + Educational Design
src
  • auth.rs15.7 KB
  • config.rs2.9 KB
  • error.rs5.2 KB
  • file_upload.rs19 KB
  • handlers.rs12.8 KB
  • lib.rs1.8 KB
  • main.rs6 KB
  • middleware.rs6.2 KB
  • static_files.rs9.9 KB
  • utils.rs9.6 KB
  • websocket.rs15.3 KB
main.rs
src/main.rs
Raw Download
Find: Go to:
/*
 * Rust Web Server - High-performance async web server
 * 
 * Created by RSK World (https://rskworld.in)
 * Founder: Molla Samser
 * Designer & Tester: Rima Khatun
 * 
 * Contact:
 * - Email: hello@rskworld.in, support@rskworld.in
 * - Phone: +91 93305 39277
 * - Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
 * 
 * © 2026 RSK World. All rights reserved.
 * Content used for educational purposes only.
 */

use clap::Parser;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use std::convert::Infallible;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use tokio;
use tracing::{error, info, warn};
use tracing_subscriber;

mod config;
mod error;
mod handlers;
mod middleware;
mod static_files;
mod utils;
mod auth;
mod file_upload;
mod websocket;

use config::ServerConfig;
use error::ServerError;
use handlers::*;
use static_files::StaticFileHandler;
use websocket::{websocket_upgrade_handler, WebSocketManager};
use file_upload::{FileManager, UploadConfig};

#[derive(Parser)]
#[command(name = "rust-web-server")]
#[command(about = "High-performance web server built with Rust")]
#[command(version = "0.1.0")]
struct Cli {
    /// Port to listen on
    #[arg(short, long, default_value = "8080")]
    port: u16,

    /// Host to bind to
    #[arg(short, long, default_value = "127.0.0.1")]
    host: String,

    /// Path to static files directory
    #[arg(short, long, default_value = "static")]
    static_dir: PathBuf,

    /// Number of worker threads
    #[arg(short, long, default_value = "4")]
    workers: usize,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Initialize tracing
    tracing_subscriber::fmt::init();

    // Parse command line arguments
    let cli = Cli::parse();

    // Load server configuration
    let config = ServerConfig::new(
        cli.host,
        cli.port,
        cli.static_dir,
        cli.workers,
    );

    info!("Starting Rust Web Server");
    info!("RSK World - https://rskworld.in");
    info!("Contact: hello@rskworld.in | +91 93305 39277");
    info!("Server will listen on {}:{}", config.host, config.port);

    // Create static file handler
    let static_handler = StaticFileHandler::new(config.static_dir.clone());

    // Create shared state
    let shared_state = handlers::SharedState::new(static_handler);

    // Make service
    let make_svc = make_service_fn(move |_conn| {
        let shared_state = shared_state.clone();
        async move {
            Ok::<_, Infallible>(service_fn(move |req| {
                let shared_state = shared_state.clone();
                async move {
                    handle_request(req, shared_state).await
                }
            }))
        }
    });

    // Create server
    let addr: SocketAddr = format!("{}:{}", config.host, config.port).parse()
        .map_err(|e| anyhow::anyhow!("Invalid address {}: {}", config.bind_address(), e))?;
    let server = Server::bind(&addr).serve(make_svc);

    info!("Server running at http://{}", addr);
    info!("Press Ctrl+C to stop the server");

    // Run server
    if let Err(e) = server.await {
        error!("Server error: {}", e);
        return Err(e.into());
    }

    Ok(())
}

async fn handle_request(
    req: Request<Body>,
    state: handlers::SharedState,
) -> Result<Response<Body>, Infallible> {
    let method = req.method().clone();
    let uri = req.uri().clone();
    let path = uri.path();

    info!("{} {}", method, path);

    let response = match (method.as_str(), path) {
        ("GET", "/") => handle_home(req, &state).await,
        ("GET", "/health") => handle_health(req, &state).await,
        ("GET", "/api/info") => handle_info(req, &state).await,
        ("GET", "/api/stats") => handle_stats(req, &state).await,
        ("POST", "/api/echo") => handle_echo(req, &state).await,
        ("GET", "/ws") | ("GET", "/websocket") => {
            // WebSocket upgrade request
            let ws_manager = Arc::new(websocket::WebSocketManager::new());
            match websocket_upgrade_handler(req, ws_manager).await {
                Ok(response) => response,
                Err(e) => e.to_response(),
            }
        }
        ("POST", "/api/upload") => {
            // File upload request
            let upload_config = file_upload::UploadConfig::default();
            let file_manager = std::sync::Arc::new(file_upload::FileManager::new(upload_config));
            let content_type = req.headers()
                .get("content-type")
                .and_then(|h| h.to_str().ok());
            match file_manager.handle_upload(req.into_body(), content_type).await {
                Ok(upload_response) => file_upload::create_upload_response(upload_response),
                Err(e) => e.to_response(),
            }
        }
        ("GET", path) if path.starts_with("/static/") => {
            handle_static_file(req, &state).await
        }
        ("GET", path) if path.starts_with("/api/") => {
            Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(Body::from("API endpoint not found"))
                .unwrap_or_else(|_| Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Body::from("Failed to create 404 response"))
                    .unwrap())
        }
        _ => {
            // Try to serve static file
            match handle_static_file(req, &state).await {
                Ok(resp) => resp,
                Err(_) => Response::builder()
                    .status(StatusCode::NOT_FOUND)
                    .body(Body::from("404 Not Found"))
                    .unwrap_or_else(|_| Response::builder()
                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                        .body(Body::from("Failed to create 404 response"))
                        .unwrap()),
            }
        }
    };

    Ok(response)
}
189 lines•6 KB
rust

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer