{"id":29640506,"url":"https://github.com/enigmatikk/torch","last_synced_at":"2025-10-14T08:14:20.806Z","repository":{"id":303988620,"uuid":"1017461713","full_name":"Enigmatikk/Torch","owner":"Enigmatikk","description":"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.","archived":false,"fork":false,"pushed_at":"2025-07-29T23:03:57.000Z","size":473,"stargazers_count":19,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-27T20:30:20.283Z","etag":null,"topics":["async","backend","hyper","middleware","performance","rest-api","rust","security","tokio","tokio-rs","web-framework"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Enigmatikk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-10T15:09:22.000Z","updated_at":"2025-09-11T07:18:11.000Z","dependencies_parsed_at":"2025-07-30T00:19:19.633Z","dependency_job_id":"3ee65bbd-65e7-4aea-9f41-2debc639191e","html_url":"https://github.com/Enigmatikk/Torch","commit_stats":null,"previous_names":["enigmatikk/torch"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Enigmatikk/Torch","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Enigmatikk%2FTorch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Enigmatikk%2FTorch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Enigmatikk%2FTorch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Enigmatikk%2FTorch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Enigmatikk","download_url":"https://codeload.github.com/Enigmatikk/Torch/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Enigmatikk%2FTorch/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279018306,"owners_count":26086334,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-14T02:00:06.444Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["async","backend","hyper","middleware","performance","rest-api","rust","security","tokio","tokio-rs","web-framework"],"created_at":"2025-07-21T21:02:06.952Z","updated_at":"2025-10-14T08:14:20.800Z","avatar_url":"https://github.com/Enigmatikk.png","language":"Rust","readme":"# Torch 🔥\n\n**The web framework that doesn't get in your way.**\n\nTorch 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.\n\n```rust\nuse torch_web::{App, Request, Response, main};\n\n#[main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error + Send + Sync\u003e\u003e {\n    let app = App::new()\n        .get(\"/\", |_req: Request| async {\n            Response::ok().body(\"Hello, World! 🔥\")\n        })\n        .get(\"/users/:id\", |req: Request| async move {\n            let id = req.param(\"id\").unwrap_or(\"Anonymous\");\n            Response::ok().body(format!(\"Hello, {}! 🔥\", id))\n        });\n\n    println!(\"🔥 Server running at http://localhost:3000\");\n    app.listen(\"127.0.0.1:3000\").await\n}\n```\n\u003ca href=\"https://buymeacoffee.com/enigmatikk\" target=\"_blank\"\u003e\u003cimg src=\"https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png\" alt=\"Buy Me A Coffee\" style=\"height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;\" \u003e\u003c/a\u003e\n\n**Why developers choose Torch:**\n- 🚀 **Blazing Fast** - Built on Tokio + Hyper for maximum performance\n- ⚡ **Compile-Time Routes** - Zero-cost route validation with type-safe extractors\n- 🔥 **Ember Templates** - Laravel Blade-inspired templating with inheritance\n- 🏗️ **Modular Architecture** - Multi-crate project structure for large applications\n- 🛡️ **Secure by Design** - Security features and beautiful error pages included\n- 📊 **Production Ready** - Monitoring, caching, and database support\n- ⚡ **Real-time Capable** - WebSocket and SSE support out of the box\n- 🎯 **Simple \u0026 Familiar** - Sinatra-inspired API that just works\n- 😄 **Fun Error Pages** - Beautiful 404 pages with rotating flame-themed messages\n- 🛠️ **Powerful CLI** - Laravel Artisan-inspired command-line tools for rapid development\n\n## ✨ Features\n\n### ⚡ **Compile-Time Route Registration**\n- **Zero-cost abstractions** - Routes validated at compile time\n- **Type-safe parameter extraction** - `Path\u003cT\u003e`, `Query\u003cT\u003e`, `Json\u003cT\u003e`\n- **IDE support** - Full autocomplete and error checking\n- **No runtime overhead** - All validation happens at build time\n\n```rust\nuse torch_web::{routes, get, Path, Query};\n\nroutes! {\n    #[get(\"/users/{id}\")]\n    async fn get_user(Path(id): Path\u003cu32\u003e) -\u003e Response {\n        Response::ok().json(format!(\"User {}\", id))\n    }\n\n    #[get(\"/users\")]\n    async fn list_users(Query(params): Query\u003cUserQuery\u003e) -\u003e Response {\n        // Type-safe query parameter extraction\n        Response::ok().json(params)\n    }\n}\n```\n\n### 🔥 **Ember Template Engine**\n- **Laravel Blade-inspired syntax** - `@extends`, `@section`, `@foreach`\n- **Template inheritance** for consistent layouts across pages\n- **Component system** with `@include` for reusable templates\n- **Automatic XSS protection** and input escaping\n- **Hot reloading** in development, intelligent caching in production\n\n```rust\nuse torch_web::{ember::*, main};\n\n#[main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error + Send + Sync\u003e\u003e {\n    let app = App::new()\n        .get(\"/\", |_req| async {\n            let data = EmberData::new()\n                .with(\"title\", \"Welcome to Torch\")\n                .with(\"users\", vec![\"Alice\", \"Bob\", \"Charlie\"]);\n\n            ember(\"home\", data).await\n        });\n\n    app.listen(\"127.0.0.1:3000\").await\n}\n```\n\n**Template file (`templates/home.ember`):**\n```html\n@extends('layout')\n\n@section('content')\n    \u003ch1\u003e{{ $title }}\u003c/h1\u003e\n\n    @if(count($users) \u003e 0)\n        \u003cul\u003e\n        @foreach($users as $user)\n            \u003cli\u003e🔥 {{ $user }}\u003c/li\u003e\n        @endforeach\n        \u003c/ul\u003e\n    @else\n        \u003cp\u003eNo users found.\u003c/p\u003e\n    @endif\n@endsection\n```\n\n### 🏗️ **Modular Architecture**\n- **Multi-crate project structure** - Prevent large monolithic crates\n- **Workspace support** - Organize code across focused crates\n- **Clear separation of concerns** - Core, Web, Auth, Database layers\n- **Team scalability** - Multiple teams can work in parallel\n\n```\nmy-torch-app/\n├── crates/\n│   ├── core/          # Business logic\n│   ├── web/           # Torch web application\n│   ├── auth/          # Authentication\n│   ├── database/      # Data layer\n│   └── api/           # External integrations\n```\n\n### 🎯 **Type-Safe Extractors**\n- **Path parameters** - Extract `:id`, `:name` with automatic type conversion\n- **Query strings** - Parse `?key=value` into structs or HashMaps\n- **JSON bodies** - Deserialize request bodies with serde\n- **Headers** - Access any HTTP header with type safety\n- **Application state** - Share data across handlers with dependency injection\n- **Multiple extractors** - Combine any extractors in a single handler\n\n### 🚀 **High Performance**\n- Built on **Tokio + Hyper** for maximum async performance\n- Handles thousands of concurrent connections efficiently\n- Zero-copy parsing and minimal allocations\n- HTTP/1.1 and HTTP/2 support\n\n### 🛡️ **Security First**\n- **Input validation** and sanitization\n- **HMAC request signing** for API security\n- **IP whitelisting** and rate limiting\n- **Security headers** and CSRF protection\n\n### 📊 **Production Ready**\n- **Structured logging** with tracing support\n- **Metrics collection** for monitoring\n- **Health checks** and graceful shutdown\n- **Configuration management** via TOML and environment variables\n\n### ⚡ **Real-time Support**\n- **WebSocket** support for real-time applications\n- **Server-Sent Events** (SSE) for live updates\n- Connection management and broadcasting\n\n### 🗄️ **Database \u0026 Caching**\n- **PostgreSQL** support with connection pooling\n- **Redis** caching integration\n- **Query builder** for safe database operations\n- **Migration runner** for schema management\n\n### � **Beautiful Error Pages**\n- **Stunning default error pages** with Torch branding\n- **Sinatra-inspired 404 messages** with flame themes\n- **Fully customizable** error page templates\n- **Responsive design** that works on all devices\n\n### 🔥 **Ember Template Engine**\n- **Laravel Blade-inspired syntax** - familiar and powerful\n- **Template inheritance** with `@extends` and `@section`\n- **Component system** for reusable templates\n- **Automatic XSS protection** and input escaping\n- **Hot reloading** and intelligent caching\n- **Zero-config setup** - just create `.ember` files\n\n### 🔧 **Developer Experience**\n- **Sinatra-inspired API** - familiar and intuitive\n- **Type-safe** request/response handling\n- **Middleware system** for composable functionality\n- **Hot reloading** in development mode\n\n## 🛠️ Developer Tools\n\n- **[VS Code Extension](https://github.com/Enigmatikk/torch-vscode)** - Syntax highlighting and IntelliSense for Ember templates\n- **[Marketplace](https://marketplace.visualstudio.com/search?term=torch%20ember\u0026target=VSCode)** - Install from VS Code Extensions\n\n```bash\n# Install VS Code extension for .ember template support\ncode --install-extension enigmatikk.torch-ember\n```\n\n## 🚀 Quick Start\n\n### Installation\n\n**For full-featured applications with templates:**\n```bash\ncargo add torch-web --features templates,json,database\n```\n\n**For API-only applications:**\n```bash\ncargo add torch-web --features json\n```\n\n**For maximum features (production apps):**\n```toml\n[dependencies]\ntorch-web = {\n    version = \"0.2.2\",\n    features = [\"templates\", \"json\", \"database\", \"cache\", \"websocket\"]\n}\n```\n\n**CLI Tool (Optional):**\n\nInstall the Torch CLI for Laravel Artisan-like functionality:\n```bash\ncargo install torch-web --features cli\n```\n\nThe CLI will automatically show PATH setup instructions for your operating system. If the `torch` command is not found after installation, follow the displayed instructions to add `~/.cargo/bin` (or `%USERPROFILE%\\.cargo\\bin` on Windows) to your system PATH.\n\nQuick CLI usage:\n```bash\ntorch new my-app        # Create new Torch application\ncd my-app\ntorch serve --hot       # Start development server with hot reload\ntorch make controller   # Generate controllers, models, etc.\ntorch --help           # Show all available commands\n```\n\n**Available Features:**\n- `templates` - Ember templating engine with Laravel Blade-like syntax\n- `json` - JSON request/response handling with serde\n- `database` - PostgreSQL support with SQLx\n- `cache` - Redis caching integration\n- `websocket` - WebSocket support for real-time apps\n- `api` - Enhanced API development tools\n- `cli` - Command-line interface with Laravel Artisan-like functionality\n- `cli` - Laravel Artisan-inspired command-line tools\n\n## 🛠️ Torch CLI - Laravel Artisan for Rust\n\nTorch includes a powerful CLI tool inspired by Laravel's Artisan, providing rapid scaffolding and development utilities:\n\n```bash\n# Install the CLI\ncargo install torch-web --features cli\n\n# Create a new Torch application\ntorch new my-app\n\n# Generate controllers, models, and more\ntorch make controller UserController --resource\ntorch make model User --migration --factory --seeder\n\n# Start development server with hot reload\ntorch serve --hot\n\n# Run database migrations\ntorch migrate\n\n# Interactive REPL for debugging\ntorch tinker\n\n# Build for production\ntorch build --release\n```\n\n### Available CLI Commands\n\n**Project Management:**\n- `torch new \u003cname\u003e` - Create new Torch application\n- `torch serve --hot` - Development server with hot reload\n- `torch build --release` - Production build with optimizations\n\n**Code Generation:**\n- `torch make controller \u003cname\u003e` - Generate controllers (with `--resource`, `--api` flags)\n- `torch make model \u003cname\u003e` - Generate models (with `--migration`, `--factory`, `--seeder` flags)\n- `torch make middleware \u003cname\u003e` - Generate middleware\n- `torch make template \u003cname\u003e` - Generate Ember templates\n- `torch make migration \u003cname\u003e` - Generate database migrations\n- `torch make test \u003cname\u003e` - Generate tests\n\n**Database Operations:**\n- `torch migrate` - Run migrations (with `rollback`, `fresh`, `status` subcommands)\n- `torch db seed` - Seed database\n- `torch db status` - Show database status\n\n**Development Tools:**\n- `torch tinker` - Interactive REPL shell\n- `torch route list` - Show all routes\n- `torch cache clear` - Clear application caches\n- `torch optimize` - Optimize for production\n\nSee the [CLI Documentation](docs/cli.md) for complete command reference and [CLI Tutorial](docs/cli-tutorial.md) for a step-by-step guide.\n\n### Hello World\n\n```rust\nuse torch_web::{App, Request, Response, main};\n\n#[main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error + Send + Sync\u003e\u003e {\n    let app = App::new()\n        .get(\"/\", |_req: Request| async {\n            Response::ok().body(\"Hello, World! 🔥\")\n        })\n        .get(\"/hello/:name\", |req: Request| async move {\n            let name = req.param(\"name\").unwrap_or(\"Anonymous\");\n            Response::ok().body(format!(\"Hello, {}! 🔥\", name))\n        })\n        .get(\"/json\", |_req: Request| async {\n            #[cfg(feature = \"json\")]\n            {\n                use serde_json::json;\n                Response::ok()\n                    .json(\u0026json!({\n                        \"message\": \"Hello from Torch!\",\n                        \"framework\": \"torch\",\n                        \"version\": \"0.1.0\"\n                    }))\n                    .unwrap()\n            }\n            #[cfg(not(feature = \"json\"))]\n            {\n                Response::ok()\n                    .content_type(\"application/json\")\n                    .body(r#\"{\"message\": \"Hello from Torch!\", \"framework\": \"torch\"}\"#)\n            }\n        });\n\n    println!(\"🔥 Starting Torch Hello World example...\");\n    app.listen(\"127.0.0.1:3000\").await\n}\n```\n\n### Try the Example\n\n```bash\n# Clone the repository\ngit clone https://github.com/Enigmatikk/torch.git\ncd torch\n\n# Run the hello world example\ncargo run --example hello_world\n\n# Visit http://localhost:3000 to see it in action!\n```\n\n## 🔥 Ember Template Engine\n\nTorch includes **Ember**, a powerful templating engine inspired by Laravel's Blade but built for Rust performance:\n\n```rust\nuse torch_web::{App, ember::*, main};\n\n#[main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error + Send + Sync\u003e\u003e {\n    let app = App::new()\n        .get(\"/\", |_req| async {\n            let data = EmberData::new()\n                .with(\"title\", \"Welcome to Torch\")\n                .with(\"users\", vec![\"Alice\", \"Bob\", \"Charlie\"]);\n\n            ember(\"home\", data).await\n        });\n\n    app.listen(\"127.0.0.1:3000\").await\n}\n```\n\n### Template Syntax\n\nCreate `templates/home.ember`:\n\n```html\n@extends('layout')\n\n@section('content')\n    \u003ch1\u003e{{ $title }}\u003c/h1\u003e\n\n    @if(count($users) \u003e 0)\n        \u003cul\u003e\n        @foreach($users as $user)\n            \u003cli\u003e🔥 {{ $user }}\u003c/li\u003e\n        @endforeach\n        \u003c/ul\u003e\n    @else\n        \u003cp\u003eNo users found.\u003c/p\u003e\n    @endif\n@endsection\n```\n\nCreate `templates/layout.ember`:\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003e{{ $title }} - My App\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cdiv class=\"container\"\u003e\n        @section('content')\n            \u003cp\u003eDefault content\u003c/p\u003e\n        @endsection\n    \u003c/div\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n### Ember Features\n\n- **🎨 Familiar Syntax**: Laravel Blade-inspired directives\n- **🏗️ Template Inheritance**: `@extends`, `@section`, `@endsection`\n- **🔄 Loops \u0026 Conditionals**: `@foreach`, `@if`, `@else`, `@endif`\n- **📦 Components**: `@include('partial')` for reusable templates\n- **🔒 Auto-Escaping**: XSS protection built-in\n- **⚡ Performance**: Compiled templates with intelligent caching\n- **🔥 Hot Reload**: Templates update automatically in development\n\n## 🚀 Real-World Example: Multi-Step Registration Wizard\n\nHere's a comprehensive example showing how Torch's features work together in a production-ready application:\n\n```rust\nuse torch_web::{App, Request, Response, main, ember::*};\nuse std::collections::HashMap;\nuse serde::{Deserialize, Serialize};\n\n// Step 1: Basic Information\n#[derive(Debug, Deserialize, Serialize, Clone)]\nstruct BasicInfo {\n    first_name: String,\n    last_name: String,\n    email: String,\n    phone: String,\n}\n\n// Registration wizard state\n#[derive(Debug, Deserialize, Serialize, Clone, Default)]\nstruct RegistrationData {\n    basic_info: Option\u003cBasicInfo\u003e,\n    current_step: u8,\n}\n\n// Session store (use Redis in production)\ntype SessionStore = std::sync::Arc\u003cstd::sync::Mutex\u003cHashMap\u003cString, RegistrationData\u003e\u003e\u003e;\n\n#[main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error + Send + Sync\u003e\u003e {\n    let sessions: SessionStore = std::sync::Arc::new(std::sync::Mutex::new(HashMap::new()));\n    let sessions_clone = sessions.clone();\n\n    let app = App::new()\n        // Home page with beautiful template\n        .get::\u003c_, ()\u003e(\"/\", |_req: Request| async {\n            let data = EmberData::new()\n                .with(\"title\", \"Welcome to Torch\")\n                .with(\"page_title\", \"Multi-Step Registration Wizard\")\n                .with(\"description\", \"Experience the power of Torch with Ember templating\");\n\n            ember(\"home\", data).await\n        })\n\n        // Registration wizard - Step 1\n        .get::\u003c_, ()\u003e(\"/register\", move |req: Request| {\n            let sessions = sessions_clone.clone();\n            async move {\n                let session_id = get_or_create_session(\u0026req);\n                let registration_data = get_session_data(\u0026sessions, \u0026session_id);\n\n                let data = EmberData::new()\n                    .with(\"title\", \"Registration - Step 1\")\n                    .with(\"step\", 1)\n                    .with(\"step_title\", \"Basic Information\")\n                    .with(\"progress\", 33)\n                    .with(\"first_name\", registration_data.basic_info\n                        .as_ref().map(|b| b.first_name.clone()).unwrap_or_default());\n\n                ember(\"registration/step1\", data).await\n            }\n        })\n\n        // Handle form submission with session state\n        .post::\u003c_, ()\u003e(\"/register/step1\", move |req: Request| {\n            let sessions = sessions.clone();\n            async move {\n                let session_id = get_or_create_session(\u0026req);\n\n                // Parse form data (simplified for example)\n                let basic_info = BasicInfo {\n                    first_name: \"John\".to_string(),\n                    last_name: \"Doe\".to_string(),\n                    email: \"john.doe@example.com\".to_string(),\n                    phone: \"+1-555-0123\".to_string(),\n                };\n\n                // Update session state\n                update_session_data(\u0026sessions, \u0026session_id, |data| {\n                    data.basic_info = Some(basic_info);\n                    data.current_step = 2;\n                });\n\n                // Redirect to next step\n                Response::redirect_found(\"/register/step2\")\n            }\n        });\n\n    println!(\"🔥 Torch Registration Wizard starting...\");\n    println!(\"🌐 Visit http://localhost:3000 to see the demo\");\n\n    app.listen(\"127.0.0.1:3000\").await\n}\n\n// Helper functions for session management\nfn get_or_create_session(req: \u0026Request) -\u003e String {\n    req.header(\"x-session-id\").unwrap_or(\"demo-session\").to_string()\n}\n\nfn get_session_data(sessions: \u0026SessionStore, session_id: \u0026str) -\u003e RegistrationData {\n    let sessions = sessions.lock().unwrap();\n    sessions.get(session_id).cloned().unwrap_or_default()\n}\n\nfn update_session_data\u003cF\u003e(sessions: \u0026SessionStore, session_id: \u0026str, updater: F)\nwhere F: FnOnce(\u0026mut RegistrationData)\n{\n    let mut sessions = sessions.lock().unwrap();\n    let mut data = sessions.get(session_id).cloned().unwrap_or_default();\n    updater(\u0026mut data);\n    sessions.insert(session_id.to_string(), data);\n}\n```\n\n**Template Structure:**\n```\ntemplates/\n├── layouts/\n│   └── main.ember          # Base layout with CSS, header, footer\n├── components/\n│   ├── header.ember        # Navigation component\n│   ├── footer.ember        # Footer component\n│   └── progress_bar.ember  # Reusable progress indicator\n└── registration/\n    ├── step1.ember         # Extends main layout\n    ├── step2.ember         # Extends main layout\n    └── step3.ember         # Extends main layout\n```\n\n**Layout Template (`templates/layouts/main.ember`):**\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003ctitle\u003e{{ $title }} - Torch Demo\u003c/title\u003e\n    \u003cstyle\u003e\n        body { font-family: 'Segoe UI', sans-serif; margin: 0; }\n        .container { max-width: 1200px; margin: 0 auto; padding: 2rem; }\n        /* Beautiful responsive CSS... */\n    \u003c/style\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    @include('components/header')\n\n    \u003cmain class=\"container\"\u003e\n        @section('content')\n            \u003cp\u003eDefault content\u003c/p\u003e\n        @endsection\n    \u003c/main\u003e\n\n    @include('components/footer')\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n**Step Template (`templates/registration/step1.ember`):**\n```html\n@extends('layouts/main')\n\n@section('content')\n    @include('components/progress_bar')\n\n    \u003cdiv class=\"form-container\"\u003e\n        \u003ch2\u003e{{ $step_title }}\u003c/h2\u003e\n\n        \u003cform method=\"POST\" action=\"/register/step1\"\u003e\n            \u003cdiv class=\"form-group\"\u003e\n                \u003clabel\u003eFirst Name\u003c/label\u003e\n                \u003cinput type=\"text\" name=\"first_name\" value=\"{{ $first_name }}\" required\u003e\n            \u003c/div\u003e\n\n            \u003cdiv class=\"form-group\"\u003e\n                \u003clabel\u003eLast Name\u003c/label\u003e\n                \u003cinput type=\"text\" name=\"last_name\" value=\"{{ $last_name }}\" required\u003e\n            \u003c/div\u003e\n\n            \u003cbutton type=\"submit\"\u003eContinue to Step 2 →\u003c/button\u003e\n        \u003c/form\u003e\n    \u003c/div\u003e\n@endsection\n```\n\nThis example demonstrates:\n- **🔥 Template inheritance** for consistent layouts\n- **📦 Component reuse** with `@include` directives\n- **🔄 Session state management** across multiple steps\n- **📝 Form handling** with validation and redirects\n- **🎨 Beautiful responsive design** with consistent theming\n- **🏗️ Modular structure** ready for team development\n\n## 🎯 Type-Safe Extractors\n\nTorch features a powerful extractors system that makes handling requests type-safe and ergonomic:\n\n```rust\nuse torch_web::{App, main, extractors::*};\nuse std::collections::HashMap;\n\n#[derive(Clone)]\nstruct AppState {\n    counter: std::sync::Arc\u003ctokio::sync::Mutex\u003cu64\u003e\u003e,\n}\n\n#[main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error + Send + Sync\u003e\u003e {\n    let state = AppState {\n        counter: std::sync::Arc::new(tokio::sync::Mutex::new(0)),\n    };\n\n    let app = App::new()\n        .with_state(state)\n\n        // Path parameters\n        .get(\"/users/:id\", |Path(user_id): Path\u003cu32\u003e| async move {\n            format!(\"User ID: {}\", user_id)\n        })\n\n        // Query parameters\n        .get(\"/search\", |Query(params): Query\u003cHashMap\u003cString, String\u003e\u003e| async move {\n            let query = params.get(\"q\").unwrap_or(\u0026\"*\".to_string());\n            format!(\"Searching for: {}\", query)\n        })\n\n        // JSON body (with json feature)\n        .post(\"/users\", |Json(user): Json\u003cserde_json::Value\u003e| async move {\n            format!(\"Creating user: {}\", user)\n        })\n\n        // Headers\n        .get(\"/info\", |Headers(headers): Headers| async move {\n            let user_agent = headers.get(\"user-agent\")\n                .and_then(|v| v.to_str().ok())\n                .unwrap_or(\"Unknown\");\n            format!(\"Your browser: {}\", user_agent)\n        })\n\n        // Application state\n        .post(\"/increment\", |State(state): State\u003cAppState\u003e| async move {\n            let mut counter = state.counter.lock().await;\n            *counter += 1;\n            format!(\"Counter: {}\", *counter)\n        })\n\n        // Multiple extractors\n        .get(\"/api/:version/search\", |\n            Path(version): Path\u003cString\u003e,\n            Query(params): Query\u003cHashMap\u003cString, String\u003e\u003e,\n            State(state): State\u003cAppState\u003e,\n        | async move {\n            let counter = state.counter.lock().await;\n            let query = params.get(\"q\").unwrap_or(\u0026\"*\".to_string());\n            format!(\"API v{}: Searching '{}' (requests: {})\", version, query, *counter)\n        });\n\n    app.listen(\"127.0.0.1:3000\").await\n}\n```\n\n### Available Extractors\n\n- **`Path\u003cT\u003e`** - Extract path parameters (`:id`, `:name`, etc.)\n- **`Query\u003cT\u003e`** - Extract query string parameters (`?key=value`)\n- **`Json\u003cT\u003e`** - Extract and deserialize JSON request bodies\n- **`Headers`** - Access request headers\n- **`State\u003cT\u003e`** - Access shared application state\n- **Multiple extractors** - Combine any extractors in a single handler\n\n## 🎨 Beautiful Error Pages\n\nOne of Torch's standout features is its beautiful, Sinatra-inspired error pages:\n\n### Fun 404 Messages\nTorch includes rotating 404 messages with flame themes:\n- *\"🔥 Torch doesn't know this ditty, but it's got plenty of other hot tracks!\"*\n- *\"🔥 This path hasn't been lit by the Torch yet.\"*\n- *\"🔥 Even the brightest flame can't illuminate this missing page.\"*\n\n### Stunning Design\n- **Modern dark theme** with professional gradients\n- **Torch branding** with beautiful SVG flame logo\n- **Fully responsive** - works on desktop, tablet, and mobile\n- **Smooth animations** and hover effects\n\n### Customizable\n```rust\nuse torch_web::ErrorPages;\n\nlet custom_pages = ErrorPages::new()\n    .custom_404(\"Your custom 404 HTML here\")\n    .custom_500(\"Your custom 500 HTML here\");\n\nlet app = App::new()\n    .error_pages(custom_pages);\n```\n\n## 🔧 Feature Flags\n\nTorch uses feature flags to keep your binary size small:\n\n- **`default`** - Includes JSON support\n- **`json`** - JSON serialization with serde\n- **`production`** - All production features (monitoring, security, etc.)\n- **`security`** - Security middleware and utilities\n- **`websocket`** - WebSocket and real-time features\n- **`database`** - PostgreSQL support with connection pooling\n- **`cache`** - Redis caching integration\n- **`api`** - API documentation generation\n- **`config`** - TOML configuration support\n- **`monitoring`** - Metrics and structured logging\n\n## 🏗️ Architecture\n\nTorch is built on proven Rust technologies:\n\n- **[Tokio](https://tokio.rs/)** - Async runtime for high performance\n- **[Hyper](https://hyper.rs/)** - Fast HTTP implementation\n- **[Tower](https://github.com/tower-rs/tower)** - Middleware and service abstractions\n- **[Serde](https://serde.rs/)** - Serialization framework\n- **[Tracing](https://tracing.rs/)** - Structured logging and diagnostics\n\n## 🔧 Configuration\n\nTorch supports configuration through TOML files and environment variables.\n\n### Configuration File\n\nCreate a `torch.toml` file in your project root:\n\n```toml\n[server]\nhost = \"0.0.0.0\"\nport = 8080\nmax_connections = 10000\nrequest_timeout_secs = 30\n\n[security]\nenable_cors = true\nenable_security_headers = true\nenable_rate_limiting = true\nper_ip_rps_limit = 100\n\n[monitoring]\nenable_metrics = true\nenable_request_logging = true\nlog_level = \"info\"\n\n[database]\nurl = \"postgresql://user:pass@localhost/db\"\nmax_connections = 10\n\n[cache]\nredis_url = \"redis://localhost:6379\"\ndefault_ttl_secs = 3600\n```\n\n### Environment Variables\n\n```bash\nexport TORCH_HOST=0.0.0.0\nexport TORCH_PORT=8080\nexport TORCH_DATABASE_URL=postgresql://user:pass@localhost/db\nexport TORCH_REDIS_URL=redis://localhost:6379\n```\n\n## 🛡️ Security Features\n\n```rust\nuse torch_web::security::*;\n\n// Input validation and sanitization\nlet app = App::new()\n    .middleware(InputValidator::new())\n    .middleware(SecurityHeaders::new())\n    .middleware(RateLimiter::new(100)); // 100 requests per second\n\n// HMAC request signing\nlet signing = RequestSigning::new(\"your-secret-key\");\nlet app = app.middleware(signing);\n\n// IP whitelisting\nlet whitelist = IpWhitelist::new()\n    .allow_ip(\"192.168.1.1\")\n    .allow_range(\"10.0.0.0/8\");\nlet app = app.middleware(whitelist);\n```\n\n## 📊 Production Features\n\n```rust\nuse torch_web::production::*;\n\n// Metrics and monitoring\nlet app = App::new()\n    .middleware(MetricsCollector::new())\n    .middleware(PerformanceMonitor::new())\n    .middleware(RequestLogger::new());\n\n// Health check endpoint\nlet app = app.get(\"/health\", |_req| async {\n    Response::ok().json(\u0026serde_json::json!({\n        \"status\": \"healthy\",\n        \"uptime\": \"24h\",\n        \"version\": \"0.1.0\"\n    })).unwrap()\n});\n```\n\n## ⚡ Advanced Features\n\n### 🏗️ Modular Project Structure\n\nTorch supports organizing large applications across multiple crates to prevent any single crate from becoming too large:\n\n```toml\n# Workspace Cargo.toml\n[workspace]\nmembers = [\n    \"crates/core\",      # Business logic\n    \"crates/web\",       # Torch web application\n    \"crates/auth\",      # Authentication\n    \"crates/database\",  # Data layer\n    \"crates/api\",       # External integrations\n]\n\n[workspace.dependencies]\ntorch-web = { version = \"0.2.2\", features = [\"templates\", \"json\"] }\n```\n\n**Benefits:**\n- ✅ **Faster builds** - Only changed crates are recompiled\n- ✅ **Parallel compilation** - Crates can be compiled in parallel\n- ✅ **Clear dependencies** - Dependency graph is explicit\n- ✅ **Team scalability** - Multiple teams can work simultaneously\n- ✅ **Code reuse** - Share components across different applications\n\n### ⚡ Compile-Time Route Validation\n\nLeverage Rust's fantastic compiler for zero-cost route registration:\n\n```rust\nuse torch_web::{routes, get, post, Path, Query, Json};\n\n// Compile-time validated routes with type-safe extractors\nroutes! {\n    #[get(\"/users/{id}\")]\n    async fn get_user(Path(id): Path\u003cu32\u003e) -\u003e Response {\n        // id is guaranteed to be a valid u32 at compile time\n        Response::ok().json(format!(\"User {}\", id))\n    }\n\n    #[get(\"/users\")]\n    async fn list_users(Query(params): Query\u003cUserQuery\u003e) -\u003e Response {\n        // params is type-checked at compile time\n        Response::ok().json(params)\n    }\n\n    #[post(\"/users\")]\n    async fn create_user(Json(user): Json\u003cCreateUserRequest\u003e) -\u003e Response {\n        // JSON deserialization is validated at compile time\n        Response::created().json(\"User created\")\n    }\n}\n```\n\n**Compile-Time Benefits:**\n- ✅ **Zero runtime overhead** - All validation happens at build time\n- ✅ **Type safety** - Parameters are type-checked by the compiler\n- ✅ **IDE support** - Full autocomplete and error checking\n- ✅ **Early error detection** - Catch route issues before deployment\n\n### 🎨 Consistent Theming System\n\nBuild applications with consistent headers, footers, and menus across multiple pages:\n\n```rust\n// Shared layout with navigation\n// templates/layouts/app.ember\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003e{{ $title }} - My App\u003c/title\u003e\n    \u003clink rel=\"stylesheet\" href=\"/css/app.css\"\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    @include('components/header')\n    @include('components/navigation')\n\n    \u003cmain class=\"content\"\u003e\n        @section('content')\n            \u003cp\u003eDefault content\u003c/p\u003e\n        @endsection\n    \u003c/main\u003e\n\n    @include('components/footer')\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n```rust\n// All pages inherit the same layout\n// templates/users/index.ember\n```html\n@extends('layouts/app')\n\n@section('content')\n    \u003ch1\u003e{{ $page_title }}\u003c/h1\u003e\n    @foreach($users as $user)\n        \u003cdiv class=\"user-card\"\u003e{{ $user.name }}\u003c/div\u003e\n    @endforeach\n@endsection\n```\n\n**Theming Benefits:**\n- ✅ **Consistent design** - Shared layouts ensure visual consistency\n- ✅ **Component reuse** - Headers, footers, menus defined once\n- ✅ **Easy maintenance** - Update navigation in one place\n- ✅ **Responsive design** - CSS and JavaScript shared across pages\n\n## 🔄 Middleware System\n\nTorch provides a powerful and flexible middleware system:\n\n```rust\nuse torch_web::middleware::*;\n\n// Built-in middleware\nlet app = App::new()\n    .middleware(Logger::new())\n    .middleware(Cors::permissive())\n    .middleware(SecurityHeaders::new())\n    .middleware(Compression::new());\n\n// Custom middleware\nlet app = app.middleware(|req: Request, next| {\n    Box::pin(async move {\n        let start = std::time::Instant::now();\n        let response = next(req).await;\n        let duration = start.elapsed();\n        println!(\"Request took: {:?}\", duration);\n        response\n    })\n});\n```\n\n## 🎯 Use Cases\n\n### Web APIs\n- **REST APIs** with JSON serialization\n- **GraphQL** endpoints\n- **Microservices** architecture\n- **Real-time applications** with WebSockets\n\n### Production Applications\n- **High-traffic websites** with caching\n- **Enterprise applications** with security\n- **Data processing** pipelines\n- **Integration services** with monitoring\n\n## 📈 Performance\n\nTorch is built for speed and efficiency:\n\n**Why Torch is fast:**\n- **Zero-copy parsing** - Minimal allocations in hot paths\n- **Async all the way down** - Built on Tokio's proven runtime\n- **Smart defaults** - Optimized configurations out of the box\n- **Efficient routing** - Fast path matching with minimal overhead\n\n**Benchmark it yourself:**\n```bash\n# Clone the repository\ngit clone https://github.com/Enigmatikk/torch.git\ncd torch\n\n# Run the hello world example\ncargo run --example hello_world --release\n\n# Test with your favorite load testing tool\nwrk -t12 -c400 -d30s http://localhost:3000/\n```\n\n## 🧪 Try It Now\n\n```bash\n# Clone and run in 30 seconds\ngit clone https://github.com/Enigmatikk/torch.git\ncd torch\n\n# Run the hello world example\ncargo run --example hello_world\n\n# Visit http://localhost:3000 to see:\n# - Hello World endpoint\n# - Path parameters (/hello/:name)\n# - JSON responses (/json)\n# - Beautiful 404 pages (try /nonexistent)\n```\n\n## 🚀 Requirements\n\n- **Rust 1.75+** (uses latest async features)\n- **Tokio runtime** (included with Torch)\n\n## 🤝 Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/Enigmatikk/torch.git\ncd torch\n\n# Run tests\ncargo test --all-features\n\n# Run examples\ncargo run --example hello_world                    # Basic routing\ncargo run --example registration_wizard --features templates,json  # Multi-step wizard\ncargo run --example ember_demo --features templates               # Template showcase\ncargo run --example enhanced_extractors            # Type-safe extractors\n\n# Check formatting\ncargo fmt --check\n\n# Run clippy\ncargo clippy --all-features\n```\n\n## 📄 License\n\nThis project is licensed under the **MIT OR Apache-2.0** license.\n\n## 🙏 Acknowledgments\n\n- **[Sinatra](http://sinatrarb.com/)** - Inspired our simple, intuitive API design\n- **[Axum](https://github.com/tokio-rs/axum)** - Architectural inspiration for middleware\n- **Rust Community** - For building an amazing ecosystem\n\n## 🚀 What's Next?\n\n1. **⭐ Star this repo** if Torch looks useful to you\n2. **🧪 Try the registration wizard** - `cargo run --example registration_wizard --features templates,json`\n3. **🔥 Explore Ember templates** - See how template inheritance and components work\n4. **🏗️ Build a modular app** - Use the multi-crate structure for large projects\n5. **⚡ Leverage compile-time routes** - Get type safety and zero-cost abstractions\n6. **🤝 Contribute** - we'd love your help making Torch even better\n\n### Join the Community\n\n- 🐛 **Found a bug?** [Open an issue](https://github.com/Enigmatikk/torch/issues)\n- 💡 **Have an idea?** [Start a discussion](https://github.com/Enigmatikk/torch/discussions)\n- 🤝 **Want to contribute?** Check out [CONTRIBUTING.md](CONTRIBUTING.md)\n- 📢 **Using Torch?** We'd love to hear your story!\n\n---\n\n**Built with ❤️ and 🔥 for developers who ship fast**\n\n*Torch - The web framework that doesn't get in your way* 🔥\n","funding_links":["https://buymeacoffee.com/enigmatikk"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fenigmatikk%2Ftorch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fenigmatikk%2Ftorch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fenigmatikk%2Ftorch/lists"}