Torch ๐ฅ
The web framework that doesn't get in your way.
Torch is a fast, secure, and production-ready web framework for Rust. Built on Tokio and Hyper, it provides everything you need to build modern web applications with minimal configuration.
use ;
async
Why developers choose Torch:
- ๐ Blazing Fast - Built on Tokio + Hyper for maximum performance
- โก Compile-Time Routes - Zero-cost route validation with type-safe extractors
- ๐ฅ Ember Templates - Laravel Blade-inspired templating with inheritance
- ๐๏ธ Modular Architecture - Multi-crate project structure for large applications
- ๐ก๏ธ Secure by Design - Security features and beautiful error pages included
- ๐ Production Ready - Monitoring, caching, and database support
- โก Real-time Capable - WebSocket and SSE support out of the box
- ๐ฏ Simple & Familiar - Sinatra-inspired API that just works
- ๐ Fun Error Pages - Beautiful 404 pages with rotating flame-themed messages
โจ Features
โก Compile-Time Route Registration
- Zero-cost abstractions - Routes validated at compile time
- Type-safe parameter extraction -
Path<T>
,Query<T>
,Json<T>
- IDE support - Full autocomplete and error checking
- No runtime overhead - All validation happens at build time
use ;
routes!
๐ฅ Ember Template Engine
- Laravel Blade-inspired syntax -
@extends
,@section
,@foreach
- Template inheritance for consistent layouts across pages
- Component system with
@include
for reusable templates - Automatic XSS protection and input escaping
- Hot reloading in development, intelligent caching in production
use ;
async
Template file (templates/home.ember
):
@extends('layout')
@section('content')
{{ $title }}
@if(count($users) > 0)
@foreach($users as $user)
๐ฅ {{ $user }}
@endforeach
@else
No users found.
@endif
@endsection
๐๏ธ Modular Architecture
- Multi-crate project structure - Prevent large monolithic crates
- Workspace support - Organize code across focused crates
- Clear separation of concerns - Core, Web, Auth, Database layers
- Team scalability - Multiple teams can work in parallel
my-torch-app/
โโโ crates/
โ โโโ core/ # Business logic
โ โโโ web/ # Torch web application
โ โโโ auth/ # Authentication
โ โโโ database/ # Data layer
โ โโโ api/ # External integrations
๐ฏ Type-Safe Extractors
- Path parameters - Extract
:id
,:name
with automatic type conversion - Query strings - Parse
?key=value
into structs or HashMaps - JSON bodies - Deserialize request bodies with serde
- Headers - Access any HTTP header with type safety
- Application state - Share data across handlers with dependency injection
- Multiple extractors - Combine any extractors in a single handler
๐ High Performance
- Built on Tokio + Hyper for maximum async performance
- Handles thousands of concurrent connections efficiently
- Zero-copy parsing and minimal allocations
- HTTP/1.1 and HTTP/2 support
๐ก๏ธ Security First
- Input validation and sanitization
- HMAC request signing for API security
- IP whitelisting and rate limiting
- Security headers and CSRF protection
๐ Production Ready
- Structured logging with tracing support
- Metrics collection for monitoring
- Health checks and graceful shutdown
- Configuration management via TOML and environment variables
โก Real-time Support
- WebSocket support for real-time applications
- Server-Sent Events (SSE) for live updates
- Connection management and broadcasting
๐๏ธ Database & Caching
- PostgreSQL support with connection pooling
- Redis caching integration
- Query builder for safe database operations
- Migration runner for schema management
๏ฟฝ Beautiful Error Pages
- Stunning default error pages with Torch branding
- Sinatra-inspired 404 messages with flame themes
- Fully customizable error page templates
- Responsive design that works on all devices
๐ฅ Ember Template Engine
- Laravel Blade-inspired syntax - familiar and powerful
- Template inheritance with
@extends
and@section
- Component system for reusable templates
- Automatic XSS protection and input escaping
- Hot reloading and intelligent caching
- Zero-config setup - just create
.ember
files
๐ง Developer Experience
- Sinatra-inspired API - familiar and intuitive
- Type-safe request/response handling
- Middleware system for composable functionality
- Hot reloading in development mode
๐ Quick Start
Installation
For full-featured applications with templates:
For API-only applications:
For maximum features (production apps):
[]
= {
version = "0.2.2",
= ["templates", "json", "database", "cache", "websocket"]
}
Available Features:
templates
- Ember templating engine with Laravel Blade-like syntaxjson
- JSON request/response handling with serdedatabase
- PostgreSQL support with SQLxcache
- Redis caching integrationwebsocket
- WebSocket support for real-time appsapi
- Enhanced API development tools
Hello World
use ;
async
Try the Example
# Clone the repository
# Run the hello world example
# Visit http://localhost:3000 to see it in action!
๐ฅ Ember Template Engine
Torch includes Ember, a powerful templating engine inspired by Laravel's Blade but built for Rust performance:
use ;
async
Template Syntax
Create templates/home.ember
:
@extends('layout')
@section('content')
{{ $title }}
@if(count($users) > 0)
@foreach($users as $user)
๐ฅ {{ $user }}
@endforeach
@else
No users found.
@endif
@endsection
Create templates/layout.ember
:
{{ $title }} - My App
@section('content')
Default content
@endsection
Ember Features
- ๐จ Familiar Syntax: Laravel Blade-inspired directives
- ๐๏ธ Template Inheritance:
@extends
,@section
,@endsection
- ๐ Loops & Conditionals:
@foreach
,@if
,@else
,@endif
- ๐ฆ Components:
@include('partial')
for reusable templates - ๐ Auto-Escaping: XSS protection built-in
- โก Performance: Compiled templates with intelligent caching
- ๐ฅ Hot Reload: Templates update automatically in development
๐ Real-World Example: Multi-Step Registration Wizard
Here's a comprehensive example showing how Torch's features work together in a production-ready application:
use ;
use HashMap;
use ;
// Step 1: Basic Information
// Registration wizard state
// Session store (use Redis in production)
type SessionStore = Arc;
async
// Helper functions for session management
Template Structure:
templates/
โโโ layouts/
โ โโโ main.ember # Base layout with CSS, header, footer
โโโ components/
โ โโโ header.ember # Navigation component
โ โโโ footer.ember # Footer component
โ โโโ progress_bar.ember # Reusable progress indicator
โโโ registration/
โโโ step1.ember # Extends main layout
โโโ step2.ember # Extends main layout
โโโ step3.ember # Extends main layout
Layout Template (templates/layouts/main.ember
):
{{ $title }} - Torch Demo
@include('components/header')
@section('content')
Default content
@endsection
@include('components/footer')
Step Template (templates/registration/step1.ember
):
@extends('layouts/main')
@section('content')
@include('components/progress_bar')
{{ $step_title }}
First Name
Last Name
Continue to Step 2 โ
@endsection
This example demonstrates:
- ๐ฅ Template inheritance for consistent layouts
- ๐ฆ Component reuse with
@include
directives - ๐ Session state management across multiple steps
- ๐ Form handling with validation and redirects
- ๐จ Beautiful responsive design with consistent theming
- ๐๏ธ Modular structure ready for team development
๐ฏ Type-Safe Extractors
Torch features a powerful extractors system that makes handling requests type-safe and ergonomic:
use ;
use HashMap;
async
Available Extractors
Path<T>
- Extract path parameters (:id
,:name
, etc.)Query<T>
- Extract query string parameters (?key=value
)Json<T>
- Extract and deserialize JSON request bodiesHeaders
- Access request headersState<T>
- Access shared application state- Multiple extractors - Combine any extractors in a single handler
๐จ Beautiful Error Pages
One of Torch's standout features is its beautiful, Sinatra-inspired error pages:
Fun 404 Messages
Torch includes rotating 404 messages with flame themes:
- "๐ฅ Torch doesn't know this ditty, but it's got plenty of other hot tracks!"
- "๐ฅ This path hasn't been lit by the Torch yet."
- "๐ฅ Even the brightest flame can't illuminate this missing page."
Stunning Design
- Modern dark theme with professional gradients
- Torch branding with beautiful SVG flame logo
- Fully responsive - works on desktop, tablet, and mobile
- Smooth animations and hover effects
Customizable
use ErrorPages;
let custom_pages = new
.custom_404
.custom_500;
let app = new
.error_pages;
๐ง Feature Flags
Torch uses feature flags to keep your binary size small:
default
- Includes JSON supportjson
- JSON serialization with serdeproduction
- All production features (monitoring, security, etc.)security
- Security middleware and utilitieswebsocket
- WebSocket and real-time featuresdatabase
- PostgreSQL support with connection poolingcache
- Redis caching integrationapi
- API documentation generationconfig
- TOML configuration supportmonitoring
- Metrics and structured logging
๐๏ธ Architecture
Torch is built on proven Rust technologies:
- Tokio - Async runtime for high performance
- Hyper - Fast HTTP implementation
- Tower - Middleware and service abstractions
- Serde - Serialization framework
- Tracing - Structured logging and diagnostics
๐ง Configuration
Torch supports configuration through TOML files and environment variables.
Configuration File
Create a torch.toml
file in your project root:
[]
= "0.0.0.0"
= 8080
= 10000
= 30
[]
= true
= true
= true
= 100
[]
= true
= true
= "info"
[]
= "postgresql://user:pass@localhost/db"
= 10
[]
= "redis://localhost:6379"
= 3600
Environment Variables
๐ก๏ธ Security Features
use *;
// Input validation and sanitization
let app = new
.middleware
.middleware
.middleware; // 100 requests per second
// HMAC request signing
let signing = new;
let app = app.middleware;
// IP whitelisting
let whitelist = new
.allow_ip
.allow_range;
let app = app.middleware;
๐ Production Features
use *;
// Metrics and monitoring
let app = new
.middleware
.middleware
.middleware;
// Health check endpoint
let app = app.get;
โก Advanced Features
๐๏ธ Modular Project Structure
Torch supports organizing large applications across multiple crates to prevent any single crate from becoming too large:
# Workspace Cargo.toml
[]
= [
"crates/core", # Business logic
"crates/web", # Torch web application
"crates/auth", # Authentication
"crates/database", # Data layer
"crates/api", # External integrations
]
[]
= { = "0.2.2", = ["templates", "json"] }
Benefits:
- โ Faster builds - Only changed crates are recompiled
- โ Parallel compilation - Crates can be compiled in parallel
- โ Clear dependencies - Dependency graph is explicit
- โ Team scalability - Multiple teams can work simultaneously
- โ Code reuse - Share components across different applications
โก Compile-Time Route Validation
Leverage Rust's fantastic compiler for zero-cost route registration:
use ;
// Compile-time validated routes with type-safe extractors
routes!
Compile-Time Benefits:
- โ Zero runtime overhead - All validation happens at build time
- โ Type safety - Parameters are type-checked by the compiler
- โ IDE support - Full autocomplete and error checking
- โ Early error detection - Catch route issues before deployment
๐จ Consistent Theming System
Build applications with consistent headers, footers, and menus across multiple pages:
// Shared layout with navigation
// templates/layouts/app.ember
```html
<!DOCTYPE html>
<html>
<head>
<title> - My title>
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
@include
@include
<main class="content">
@section
<p>Default p>
@endsection
</main>
@include
</body>
</html>
// All pages inherit the same layout
// templates/users/index.ember
```html
@extends
@section
<h1></h1>
@foreach
<div class="user-card"></div>
@endforeach
@endsection
Theming Benefits:
- โ Consistent design - Shared layouts ensure visual consistency
- โ Component reuse - Headers, footers, menus defined once
- โ Easy maintenance - Update navigation in one place
- โ Responsive design - CSS and JavaScript shared across pages
๐ Middleware System
Torch provides a powerful and flexible middleware system:
use *;
// Built-in middleware
let app = new
.middleware
.middleware
.middleware
.middleware;
// Custom middleware
let app = app.middleware;
๐ฏ Use Cases
Web APIs
- REST APIs with JSON serialization
- GraphQL endpoints
- Microservices architecture
- Real-time applications with WebSockets
Production Applications
- High-traffic websites with caching
- Enterprise applications with security
- Data processing pipelines
- Integration services with monitoring
๐ Performance
Torch is built for speed and efficiency:
Why Torch is fast:
- Zero-copy parsing - Minimal allocations in hot paths
- Async all the way down - Built on Tokio's proven runtime
- Smart defaults - Optimized configurations out of the box
- Efficient routing - Fast path matching with minimal overhead
Benchmark it yourself:
# Clone the repository
# Run the hello world example
# Test with your favorite load testing tool
๐งช Try It Now
# Clone and run in 30 seconds
# Run the hello world example
# Visit http://localhost:3000 to see:
# - Hello World endpoint
# - Path parameters (/hello/:name)
# - JSON responses (/json)
# - Beautiful 404 pages (try /nonexistent)
๐ Requirements
- Rust 1.75+ (uses latest async features)
- Tokio runtime (included with Torch)
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
# Clone the repository
# Run tests
# Run examples
# Check formatting
# Run clippy
๐ License
This project is licensed under the MIT OR Apache-2.0 license.
๐ Acknowledgments
- Sinatra - Inspired our simple, intuitive API design
- Axum - Architectural inspiration for middleware
- Rust Community - For building an amazing ecosystem
๐ What's Next?
- โญ Star this repo if Torch looks useful to you
- ๐งช Try the registration wizard -
cargo run --example registration_wizard --features templates,json
- ๐ฅ Explore Ember templates - See how template inheritance and components work
- ๐๏ธ Build a modular app - Use the multi-crate structure for large projects
- โก Leverage compile-time routes - Get type safety and zero-cost abstractions
- ๐ค Contribute - we'd love your help making Torch even better
Join the Community
- ๐ Found a bug? Open an issue
- ๐ก Have an idea? Start a discussion
- ๐ค Want to contribute? Check out CONTRIBUTING.md
- ๐ข Using Torch? We'd love to hear your story!
Built with โค๏ธ and ๐ฅ for developers who ship fast
Torch - The web framework that doesn't get in your way ๐ฅ