Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Welcome to the official Lumine guide!

Lumine is an asynchronous HTTP web server framework written in Rust. It is designed with a focus on simplicity, high performance, and an ergonomic developer experience.

Why Lumine?

  • Asynchronous by Default: Built on top of the tokio runtime, Lumine can handle thousands of concurrent connections with minimal overhead.
  • Ergonomic & Simple: Provides a clean and intuitive API, similar to modern frameworks in other languages (like Express.js in Node or Axum in the Rust ecosystem).
  • Type-Safe: Leverages Rust’s type system to ensure request validation and response generation are verified at compile time.
  • Extensible: Supports a powerful Middleware system to easily add cross-cutting features like logging, authentication, CORS, and global error handling.

Key Features

  1. Dynamic Routing: Supports static routes, dynamic path parameters (/users/:id), and query parameters (?sort=date).
  2. Header & Body Inspection: Easy data extraction from HTTP requests, including automatic JSON parsing via serde.
  3. Ergonomic Response Conversion: The IntoResponse trait allows returning various types (such as &str, String, StatusCode, and tuples) directly from your route handlers.
  4. File Streaming: Support for memory-efficient file delivery using the built-in filestream feature.

Installation & Quick Start

To start using Lumine, ensure you have the Rust compiler and cargo installed on your system.

Adding Dependencies

Add lumine and other supporting dependencies to your project’s Cargo.toml:

[dependencies]
lumine = { version = "0" }
tokio = { version = "1", features = ["full"] }
anyhow = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Note: Within this workspace, you can refer to the local lumine folder.


Your First “Hello World” Application

Create a new file at src/main.rs and write the following code:

use lumine::prelude::*;
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // 1. Build the application with a "/" route
    let app = Lumine::builder()
        .route("/", hello_handler)
        .build();

    // 2. Bind to localhost:8080
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    println!("✅ Server running at http://127.0.0.1:8080");

    // 3. Serve the application
    app.serve(listener).await;

    Ok(())
}

// Simple route handler that returns "Hello, World!"
async fn hello_handler(_req: Request) -> impl IntoResponse {
    "Hello, World!"
}

Running the Server

Run the server using cargo:

cargo run

Open a new terminal or use your browser to access the endpoint:

curl http://127.0.0.1:8080
# Output: Hello, World!

Routing & Parameters

Lumine provides a highly flexible path-based dynamic routing system. You can register routes directly using Lumine::builder().route(...).

Registering Static Routes

Static routes are perfect for pages that don’t require dynamic parameters in their URLs.

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/", index_handler)
        .route("/about", about_handler)
        .route("/api/v1/status", status_handler)
        .build();
    
    // ... run server
}

Path Parameters

Lumine supports defining dynamic parameters in the path using the colon (:id) syntax.

Route Registration Example

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/users/:id", get_user_handler)
        .route("/users/:user_id/posts/:postId", get_post_handler)
        .build();
    
    // ... run server
}

Extracting Path Parameters

Inside a route handler, you can use the Params::from_request helper to extract these parameters:

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/users/:id", get_user_handler)
        .build();

    // ... run server
}

async fn get_user_handler(req: Request) -> impl IntoResponse {
    // Extract path parameters from the request
    let params = Params::from_request(&req);

    // Retrieve the parameter by the name registered in the route
    let user_id = match params.get("id") {
        Some(id) => id,
        None => return (StatusCode::BAD_REQUEST, "Missing user id").into_response(),
    };

    format!("Fetching data for user with ID: {}", user_id).into_response()
}

Query Parameters

Query parameters are optional parameters sent at the end of the URL (e.g., ?search=rust&limit=10). You do not need to register them in the route definition; simply extract them within the handler.

Extracting Query Parameters

Use the Query::from_request helper to retrieve query parameters:

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/search", search_handler)
        .build();

    // ... run server
}

async fn search_handler(req: Request) -> impl IntoResponse {
    // Extract query parameters from the request
    let query_params = Query::from_request(&req);

    // Retrieve the "q" parameter (search query)
    let search_query = query_params.get("q").unwrap_or("default_search");

    // Retrieve the "limit" parameter, parsing it to a numeric type
    let limit = query_params
        .get("limit")
        .and_then(|l| l.parse::<usize>().ok())
        .unwrap_or(10); // Default value if limit is missing or invalid

    format!("Search results for '{}' with limit: {}", search_query, limit)
}

Handling Requests

Each route handler receives a Request parameter, which provides full access to all HTTP data sent by the client.

Reading Method, URI, and Headers

You can easily access basic details of the Request object:

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/", request_info_handler)
        .build();

    // ... run server
}

async fn request_info_handler(req: Request) -> impl IntoResponse {
    // Read the HTTP Method (GET, POST, etc.)
    let method = req.method().to_string();

    // Read the Request URI
    let uri = req.uri().to_string();

    // Read a specific Header
    let user_agent = req
        .headers()
        .get("user-agent")
        .and_then(|val| val.to_str().ok())
        .unwrap_or("Unknown");

    format!(
        "Method: {}\nURI: {}\nUser-Agent: {}",
        method, uri, user_agent
    )
}

Reading the Request Body

Lumine stores the request body bytes directly in the Request struct. You can access these bytes via req.body().

Parsing JSON from the Body

To read JSON sent by the client, you can combine Lumine with the serde_json crate to perform safe deserialization:

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/users", create_user_handler)
        .build();

    // ... run server
}

use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUserDto {
    username: String,
    email: String,
}

async fn create_user_handler(req: Request) -> impl IntoResponse {
    // Ensure the HTTP Method is POST
    if req.method() != "POST" {
        return (StatusCode::METHOD_NOT_ALLOWED, "Method must be POST").into_response();
    }

    // Parse the body bytes into the struct
    let payload: CreateUserDto = match serde_json::from_slice(req.body()) {
        Ok(data) => data,
        Err(err) => {
            return (
                StatusCode::BAD_REQUEST,
                format!("Invalid JSON: {}", err)
            ).into_response();
        }
    };

    format!("User '{}' successfully created!", payload.username).into_response()
}

Generating Responses

Lumine uses the IntoResponse trait to automatically convert values returned by handlers into valid HTTP responses. This gives developers the flexibility to return the data type that best fits their needs.

Built-in Types Supporting IntoResponse

By default, Lumine provides IntoResponse implementations for many common types:

1. Plain Text (&'static str and String)

Automatically generates a 200 OK response with a Content-Type: text/plain header.

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/plain", handler)
        .build();

    // ... run server
}

async fn handler(_req: Request) -> impl IntoResponse {
    "This is plain text"
}

2. Status Code (StatusCode)

Generates an empty response with the specified HTTP status.

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/not-found", not_found_handler)
        .build();

    // ... run server
}

async fn not_found_handler(_req: Request) -> impl IntoResponse {
    StatusCode::NOT_FOUND
}

Using Tuples for Flexible Responses

If you need to customize the HTTP status or add additional headers, Lumine supports returning tuples:

(StatusCode, Body)

Specify the status code and body together.

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/created", created_handler)
        .build();

    // ... run server
}

async fn created_handler(_req: Request) -> impl IntoResponse {
    (StatusCode::CREATED, "Resource successfully created")
}

(HeaderMap, Body)

Specify custom headers and a body. The status defaults to 200 OK.

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/custom-header", custom_header_handler)
        .build();

    // ... run server
}

async fn custom_header_handler(_req: Request) -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert("X-App-Version", "1.0.0".parse().unwrap());

    (headers, "Text with custom header")
}

(StatusCode, HeaderMap, Body)

Customize the status code, headers, and body all at once. This gives you full control over your response.

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/full-response", full_response_handler)
        .build();

    // ... run server
}

async fn full_response_handler(_req: Request) -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert("Content-Type", "application/json".parse().unwrap());

    let json_data = r#"{"status": "ok"}"#;

    (StatusCode::OK, headers, json_data)
}

Streaming Files

If you enable the filestream feature, Lumine provides asynchronous handling to stream files directly from your filesystem efficiently:

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/download", download_image_handler)
        .build();

    // ... run server
}

use lumine::filestream::{FileStream, Disposition};

async fn download_image_handler(_req: Request) -> impl IntoResponse {
    // Open file in inline mode (displayed in browser) or attachment mode (downloaded)
    match FileStream::open_with_disposition("assets/logo.png", Disposition::Attachment).await {
        Ok(stream) => stream.into_response(),
        Err(_) => (StatusCode::NOT_FOUND, "File not found").into_response(),
    }
}

Middleware

Middleware in Lumine allows you to run code before a request reaches the main handler (pre-processing) and after the handler returns a response (post-processing). This is ideal for cross-cutting concerns like logging, authentication, CORS, compression, etc.

Defining Custom Middleware

To create a new middleware, define a struct and implement the Middleware trait:

use lumine::prelude::*;

#[tokio::main]
async fn main() {}

struct RequestLogger;

#[async_trait::async_trait]
impl Middleware for RequestLogger {
    async fn handle(&self, request: Request, next: Next) -> Response {
        // 1. Pre-processing: Executed BEFORE the request reaches the handler
        println!("🌍 Incoming request: {} {}", request.method(), request.uri());

        // 2. Run the rest of the chain (other middleware or the handler)
        let response = next.run(request).await;

        // 3. Post-processing: Executed AFTER the handler finishes
        println!("🌍 Finished processing. Response status: {}", response.status());

        // Return the response object
        response
    }
}

Registering Global Middleware

Global middleware is applied to all registered routes in the application. Register it using .middleware(...) on your application builder.

use lumine::prelude::*;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let app = Lumine::builder()
        .route("/", home_handler)
        .route("/about", about_handler)
        // Register RequestLogger as global middleware
        .middleware(RequestLogger)
        .build();

    // ... run server
}

Registering Route-Specific Middleware

If you only want to apply middleware to specific routes (e.g., an /admin route requiring authentication), you can use the .route_with(...) method:

use lumine::prelude::*;

struct AuthMiddleware;

#[async_trait::async_trait]
impl Middleware for AuthMiddleware {
    async fn handle(&self, request: Request, next: Next) -> Response {
        // Token verification logic here
        let is_authenticated = check_token(&request);

        if !is_authenticated {
            // Intercept the request and immediately return 401 Unauthorized
            return (StatusCode::UNAUTHORIZED, "Access denied").into_response();
        }

        next.run(request).await
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let app = Lumine::builder()
        // Public route
        .route("/", home_handler)
        // Protected route with specific middleware
        .route_with("/admin", admin_dashboard_handler, |r| {
            r.middleware(AuthMiddleware).run_before_global()
        })
        .middleware(RequestLogger) // Global logger still runs
        .build();
    
    // ... run server
}

Error Handling

Robust error handling is a key requirement for high-quality web servers. Lumine leverages Rust’s safe error handling system and provides deep integration with HTTP status codes.

Returning Result from Handlers

Lumine implements the IntoResponse trait for std::result::Result<T, T> where T implements IntoResponse. This allows you to use the ? operator to streamline your handler’s asynchronous logic:

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/users", db_fetch_handler)
        .build();

    // ... run server
}

async fn db_fetch_handler(req: Request) -> Result<String, StatusCode> {
    let user_id = extract_user_id(&req)?; // Returns Err(StatusCode::BAD_REQUEST) on failure

    match fetch_user_from_db(user_id).await {
        Ok(user) => Ok(format!("Hello, {}", user.name)),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

Mapping System Errors to HTTP Status Codes

Lumine has an internal Error enum that automatically maps protocol and parsing issues to appropriate HTTP status codes:

  • Error::UriTooLarge -> 414 URI TOO LONG
  • Error::BodyTooLarge -> 413 PAYLOAD TOO LARGE
  • Error::HeadersTooLarge -> 431 REQUEST HEADER FIELDS TOO LARGE
  • Error::QueryTooLarge -> 414 URI TOO LONG
  • Error::HttpVersionNotSupported -> 505 HTTP VERSION NOT SUPPORTED
  • Error::InvalidRequestLine / Error::InvalidHeaders -> 400 BAD REQUEST
  • Error::Unimplemented -> 501 NOT IMPLEMENTED

If any of these errors occur while receiving a request, Lumine intercepts the request and gracefully returns the corresponding HTTP response without crashing the server.


Creating Application-Specific Custom Errors

For larger applications, it is highly recommended to create a custom error enum and implement IntoResponse to map internal errors to user-friendly HTTP responses:

use lumine::prelude::*;

#[tokio::main]
async fn main() {
    let app = Lumine::builder()
        .route("/users", get_user_profile)
        .build();

    // ... run server
}

use serde::Serialize;

#[derive(Debug)]
enum AppError {
    NotFound(String),
    DatabaseError,
    ValidationError(String),
}

#[derive(Serialize)]
struct ErrorPayload {
    error: String,
    message: String,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound(res) => (StatusCode::NOT_FOUND, format!("Resource '{}' not found", res)),
            AppError::DatabaseError => (StatusCode::INTERNAL_SERVER_ERROR, "Internal database error occurred".to_string()),
            AppError::ValidationError(msg) => (StatusCode::BAD_REQUEST, msg),
        };

        let payload = ErrorPayload {
            error: format!("{:?}", self),
            message,
        };

        let json_body = serde_json::to_string(&payload).unwrap();

        let mut headers = HeaderMap::new();
        headers.insert("Content-Type", "application/json".parse().unwrap());

        (status, headers, json_body).into_response()
    }
}

// Your handler remains extremely clean and safe:
async fn get_user_profile(req: Request) -> Result<String, AppError> {
    let id = extract_id(&req).map_err(|_| AppError::ValidationError("Invalid ID".to_string()))?;
    
    let user = db_query_user(id).await
        .map_err(|_| AppError::DatabaseError)?
        .ok_or_else(|| AppError::NotFound("User".to_string()))?;

    Ok(serde_json::to_string(&user).unwrap())
}