torch-web 0.2.0

Fast, secure web framework for Rust with production-ready features out of the box
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# 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.

```rust
use torch_web::{App, Request, Response, main};

#[main]

async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let app = App::new()
        .get("/", |_req: Request| async {
            Response::ok().body("Hello, World! ๐Ÿ”ฅ")
        })
        .get("/users/:id", |req: Request| async move {
            let id = req.param("id").unwrap_or("Anonymous");
            Response::ok().body(format!("Hello, {}! ๐Ÿ”ฅ", id))
        });

    println!("๐Ÿ”ฅ Server running at http://localhost:3000");
    app.listen("127.0.0.1:3000").await
}
```
<a href="https://buymeacoffee.com/enigmatikk" target="_blank"><img 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;" ></a>

**Why developers choose Torch:**
- ๐Ÿš€ **Blazing Fast** - Built on Tokio + Hyper for maximum performance
- ๐Ÿ›ก๏ธ **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


### ๐Ÿš€ **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

### ๐Ÿ”ง **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


Add Torch to your `Cargo.toml`:

```toml
[dependencies]
# Basic usage - no need for tokio dependency!

torch-web = "0.2.0"

# For JSON support (recommended)

torch-web = { version = "0.2.0", features = ["json"] }

# For production features

torch-web = { version = "0.2.0", features = ["production"] }

# All features

torch-web = { version = "0.2.0", features = ["production", "websocket", "database", "cache"] }
```

### Hello World


```rust
use torch_web::{App, Request, Response, main};

#[main]

async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let app = App::new()
        .get("/", |_req: Request| async {
            Response::ok().body("Hello, World! ๐Ÿ”ฅ")
        })
        .get("/hello/:name", |req: Request| async move {
            let name = req.param("name").unwrap_or("Anonymous");
            Response::ok().body(format!("Hello, {}! ๐Ÿ”ฅ", name))
        })
        .get("/json", |_req: Request| async {
            #[cfg(feature = "json")]
            {
                use serde_json::json;
                Response::ok()
                    .json(&json!({
                        "message": "Hello from Torch!",
                        "framework": "torch",
                        "version": "0.1.0"
                    }))
                    .unwrap()
            }
            #[cfg(not(feature = "json"))]
            {
                Response::ok()
                    .content_type("application/json")
                    .body(r#"{"message": "Hello from Torch!", "framework": "torch"}"#)
            }
        });

    println!("๐Ÿ”ฅ Starting Torch Hello World example...");
    app.listen("127.0.0.1:3000").await
}
```

### Try the Example


```bash
# Clone the repository

git clone https://github.com/Enigmatikk/torch.git
cd torch

# Run the hello world example

cargo run --example hello_world

# Visit http://localhost:3000 to see it in action!

```

## ๐ŸŽจ 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

```rust
use torch_web::ErrorPages;

let custom_pages = ErrorPages::new()
    .custom_404("Your custom 404 HTML here")
    .custom_500("Your custom 500 HTML here");

let app = App::new()
    .error_pages(custom_pages);
```

## ๐Ÿ”ง Feature Flags


Torch uses feature flags to keep your binary size small:

- **`default`** - Includes JSON support
- **`json`** - JSON serialization with serde
- **`production`** - All production features (monitoring, security, etc.)
- **`security`** - Security middleware and utilities
- **`websocket`** - WebSocket and real-time features
- **`database`** - PostgreSQL support with connection pooling
- **`cache`** - Redis caching integration
- **`api`** - API documentation generation
- **`config`** - TOML configuration support
- **`monitoring`** - Metrics and structured logging

## ๐Ÿ—๏ธ Architecture


Torch is built on proven Rust technologies:

- **[Tokio]https://tokio.rs/** - Async runtime for high performance
- **[Hyper]https://hyper.rs/** - Fast HTTP implementation
- **[Tower]https://github.com/tower-rs/tower** - Middleware and service abstractions
- **[Serde]https://serde.rs/** - Serialization framework
- **[Tracing]https://tracing.rs/** - 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:

```toml
[server]
host = "0.0.0.0"
port = 8080
max_connections = 10000
request_timeout_secs = 30

[security]
enable_cors = true
enable_security_headers = true
enable_rate_limiting = true
per_ip_rps_limit = 100

[monitoring]
enable_metrics = true
enable_request_logging = true
log_level = "info"

[database]
url = "postgresql://user:pass@localhost/db"
max_connections = 10

[cache]
redis_url = "redis://localhost:6379"
default_ttl_secs = 3600
```

### Environment Variables


```bash
export TORCH_HOST=0.0.0.0
export TORCH_PORT=8080
export TORCH_DATABASE_URL=postgresql://user:pass@localhost/db
export TORCH_REDIS_URL=redis://localhost:6379
```

## ๐Ÿ›ก๏ธ Security Features


```rust
use torch_web::security::*;

// Input validation and sanitization
let app = App::new()
    .middleware(InputValidator::new())
    .middleware(SecurityHeaders::new())
    .middleware(RateLimiter::new(100)); // 100 requests per second

// HMAC request signing
let signing = RequestSigning::new("your-secret-key");
let app = app.middleware(signing);

// IP whitelisting
let whitelist = IpWhitelist::new()
    .allow_ip("192.168.1.1")
    .allow_range("10.0.0.0/8");
let app = app.middleware(whitelist);
```

## ๐Ÿ“Š Production Features


```rust
use torch_web::production::*;

// Metrics and monitoring
let app = App::new()
    .middleware(MetricsCollector::new())
    .middleware(PerformanceMonitor::new())
    .middleware(RequestLogger::new());

// Health check endpoint
let app = app.get("/health", |_req| async {
    Response::ok().json(&serde_json::json!({
        "status": "healthy",
        "uptime": "24h",
        "version": "0.1.0"
    })).unwrap()
});
```

## ๐Ÿ”„ Middleware System

Torch provides a powerful and flexible middleware system:

```rust
use torch_web::middleware::*;

// Built-in middleware
let app = App::new()
    .middleware(Logger::new())
    .middleware(Cors::permissive())
    .middleware(SecurityHeaders::new())
    .middleware(Compression::new());

// Custom middleware
let app = app.middleware(|req: Request, next| {
    Box::pin(async move {
        let start = std::time::Instant::now();
        let response = next(req).await;
        let duration = start.elapsed();
        println!("Request took: {:?}", duration);
        response
    })
});
```

## ๐ŸŽฏ 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:**
```bash
# Clone the repository

git clone https://github.com/Enigmatikk/torch.git
cd torch

# Run the hello world example

cargo run --example hello_world --release

# Test with your favorite load testing tool

wrk -t12 -c400 -d30s http://localhost:3000/
```

## ๐Ÿงช Try It Now


```bash
# Clone and run in 30 seconds

git clone https://github.com/Enigmatikk/torch.git
cd torch

# Run the hello world example

cargo run --example hello_world

# 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](CONTRIBUTING.md) for details.

### Development Setup


```bash
# Clone the repository

git clone https://github.com/Enigmatikk/torch.git
cd torch

# Run tests

cargo test --all-features

# Run the example

cargo run --example hello_world

# Check formatting

cargo fmt --check

# Run clippy

cargo clippy --all-features
```

## ๐Ÿ“„ License


This project is licensed under the **MIT OR Apache-2.0** license.

## ๐Ÿ™ Acknowledgments


- **[Sinatra]http://sinatrarb.com/** - Inspired our simple, intuitive API design
- **[Axum]https://github.com/tokio-rs/axum** - Architectural inspiration for middleware
- **Rust Community** - For building an amazing ecosystem

## ๐Ÿš€ What's Next?


1. **โญ Star this repo** if Torch looks useful to you
2. **๐Ÿงช Try the example** to see how it feels
3. **๐Ÿ”ฅ Build something awesome** and let us know about it
4. **๐Ÿค Contribute** - we'd love your help making Torch even better

### Join the Community


- ๐Ÿ› **Found a bug?** [Open an issue]https://github.com/Enigmatikk/torch/issues
- ๐Ÿ’ก **Have an idea?** [Start a discussion]https://github.com/Enigmatikk/torch/discussions
- ๐Ÿค **Want to contribute?** Check out [CONTRIBUTING.md]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* ๐Ÿ”ฅ