ignitia 0.1.3

A blazing fast, lightweight web framework for Rust that ignitias your development
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# ๐Ÿ”ฅ Ignitia

<div align="center">

<img src="https://raw.githubusercontent.com/AarambhDevHub/ignitia/main/assets/ignitia-logo.png" alt="Ignitia Logo" width="200">

**A blazing fast, lightweight web framework for Rust that ignitias your development journey.**

*Embodies the spirit of **Aarambh** (new beginnings) - the spark that ignitias your web development journey*

**Built with โค๏ธ by [Aarambh Dev Hub](https://youtube.com/@aarambhdevhub)**

[![Crates.io](https://img.shields.io/crates/v/ignitia.svg?style=for-the-badge&logo=rust&color=orange&labelColor=black)](https://crates.io/crates/ignitia)
[![Downloads](https://img.shields.io/crates/d/ignitia.svg?style=for-the-badge&color=red&labelColor=black)](https://crates.io/crates/ignitia)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge&labelColor=black)](https://opensource.org/licenses/MIT)

[![Build Status](https://img.shields.io/github/actions/workflow/status/AarambhDevHub/ignitia/ci.yml?branch=main&style=for-the-badge&logo=github&labelColor=black)](https://github.com/AarambhDevHub/ignitia/actions)
[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg?style=for-the-badge&logo=rust&labelColor=black)](https://www.rust-lang.org/)
[![Docs](https://img.shields.io/docsrs/ignitia?style=for-the-badge&logo=rust&color=blue&labelColor=black)](https://docs.rs/ignitia)

[![GitHub Stars](https://img.shields.io/github/stars/AarambhDevHub/ignitia?style=social&logo=github)](https://github.com/AarambhDevHub/ignitia/stargazers)
[![YouTube](https://img.shields.io/youtube/channel/subscribers/UCm5U5uQiZA_mQY5wQ6WfUVA?style=social&logo=youtube&label=Aarambh%20Dev%20Hub)](https://youtube.com/@aarambhdevhub)

<img src="https://raw.githubusercontent.com/AarambhDevHub/ignitia/main/assets/ignitia-banner.png" alt="Ignitia Banner" width="100%">

</div>

---

## โšก Why Ignitia?

Ignitia embodies the spirit of **Aarambh** (new beginnings) - the spark that ignitias your web development journey. Built for developers who demand speed, simplicity, and power.

- **๐Ÿš€ Blazing Fast**: Built on Hyper and Tokio for maximum async performance
- **๐Ÿชถ Lightweight**: Minimal overhead, maximum efficiency
- **๐Ÿ”ฅ Powerful**: Advanced routing, middleware, and built-in features
- **โšก Energetic**: Modern APIs that energize your development
- **๐ŸŽฏ Developer-First**: Clean, intuitive, and productive
- **๐Ÿ›ก๏ธ Secure**: Built-in security features and best practices
- **๐Ÿช Cookie Management**: Full-featured cookie handling with security attributes
- **๐Ÿ”ง Middleware**: Composable middleware architecture for cross-cutting concerns

---

## ๐Ÿ“‹ Table of Contents

- [Installation]#-installation
- [Quick Start]#-quick-start
- [Core Features]#-core-features
- [Routing]#-routing
- [Middleware]#-middleware
- [Cookie Management]#-cookie-management
- [Authentication]#-authentication
- [Examples]#-examples
- [API Reference]#-api-reference
- [Testing]#-testing
- [Performance]#-performance
- [Contributing]#-contributing
- [License]#-license

---

## ๐Ÿ› ๏ธ Installation

Add Ignitia to your `Cargo.toml`:

```
[dependencies]
ignitia = "0.1.2"
tokio = { version = "1.40", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tracing-subscriber = "0.3"
```

---

## ๐Ÿš€ Quick Start

Create your first Ignitia application:

```rust
use ignitia::{
    Router, Server, Response, Result,
    handler_fn,
    handler::extractor::{Path, Query, Json, Body, Extension},
};
use serde::Deserialize;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    let shared_state = Arc::new(AppState { app_name: "IgnitiaApp".to_string() });

    let router = Router::new()
        // Simple route with no params
        .get("/", handler_fn(root_handler))
        // Route with path params
        .get("/users/:id", get_user)
        // Route with query params extractor
        .get("/search", search_handler)
        // Route to create user with JSON body
        .post("/users", create_user)
        // Route using raw Body extractor
        .post("/upload", upload_handler)
        // Route using extension for shared state
        .get("/info", with_state)
    ;

    let router = router.middleware(StateExtensionMiddleware::new(shared_state.clone()));

    let server = Server::new(router, "127.0.0.1:3000".parse().unwrap());

    println!("๐Ÿ”ฅ Igniting server at http://127.0.0.1:3000");
    server.ignitia().await?;

    Ok(())
}

async fn root_handler() -> Result<Response> {
    Ok(Response::html("<h1>๐Ÿ”ฅ Welcome to Ignitia!</h1>"))
}

async fn get_user(Path(params): Path<(String,)>) -> Result<Response> {
    let user_id = &params.0;
    Ok(Response::json(serde_json::json!({ "user_id": user_id }))?)
}

#[derive(Deserialize)]
struct SearchParams {
    q: String,
    limit: Option<u32>,
}

async fn search_handler(Query(params): Query<SearchParams>) -> Result<Response> {
    Ok(Response::json(serde_json::json!({
        "query": params.q,
        "limit": params.limit.unwrap_or(10)
    }))?)
}

#[derive(Deserialize)]
struct NewUser {
    name: String,
    email: String,
}

async fn create_user(Json(user): Json<NewUser>) -> Result<Response> {
    // Simulate saving user
    Ok(Response::json(serde_json::json!({
        "status": "created",
        "user": user
    }))?)
}

async fn upload_handler(Body(body): Body) -> Result<Response> {
    Ok(Response::text(format!("Uploaded {} bytes", body.len())))
}

struct AppState {
    app_name: String,
}

async fn with_state(Extension(state): Extension<Arc<AppState>>) -> Result<Response> {
    Ok(Response::text(format!("App name: {}", state.app_name)))
}

// Middleware to inject state into request extensions (see below)
struct StateExtensionMiddleware(Arc<AppState>);
impl StateExtensionMiddleware {
    fn new(state: Arc<AppState>) -> Self {
        Self(state)
    }
}

#[async_trait::async_trait]
impl ignitia::middleware::Middleware for StateExtensionMiddleware {
    async fn before(&self, req: &mut ignitia::Request) -> ignitia::Result<()> {
        req.insert_extension(self.0.clone());
        Ok(())
    }
}
```

---

## ๐Ÿ”ฅ Core Features

### ๐Ÿ›ฃ๏ธ Routing Examples

#### Path Parameter Extraction

```rust
async fn get_post(Path((user_id, post_id)): Path<(String, String)>) -> Result<Response> {
    Ok(Response::text(format!("User: {}, Post: {}", user_id, post_id)))
}

let router = Router::new()
    .get("/users/:user_id/posts/:post_id", handler_fn(get_post));
```

#### Query Parameter Extraction

```rust
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    per_page: Option<u32>,
}

async fn list_items(Query(pagination): Query<Pagination>) -> Result<Response> {
    Ok(Response::json(&pagination)?)
}
```

#### JSON Body Parsing

```rust
#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: String,
}

async fn login(Json(form): Json<LoginForm>) -> Result<Response> {
    // Authenticate
    Ok(Response::text(format!("Welcome, {}!", form.username)))
}
```

#### Raw Body Usage

```rust
async fn raw_upload(Body(body): Body) -> Result<Response> {
    Ok(Response::text(format!("Received {} bytes", body.len())))
}
```

#### Using Shared State via Extensions

```rust
use std::sync::Arc;

struct AppConfig {
    version: String,
}

async fn version_info(Extension(config): Extension<Arc<AppConfig>>) -> Result<Response> {
    Ok(Response::text(format!("App version: {}", config.version)))
}
```

### **Wildcard Routes**

```rust
// Serve static files: /*path matches any path
.get("/*path", serve_static)

async fn serve_static() -> Result<Response> {
    let path = req.param("path").unwrap();
    // Serve file from static directory with security checks
    serve_file_from_directory("./static", path).await
}
```


### **๐Ÿช Built-in Cookie Management**

Secure, easy-to-use cookie handling with all security attributes:

```rust
use ignitia::{Cookie, SameSite};

// Set secure cookies
let session = Cookie::new("session", "user123")
    .path("/")
    .max_age(3600) // 1 hour
    .http_only()
    .secure()
    .same_site(SameSite::Lax);

let response = Response::text("Session ignitiad!")
    .add_cookie(session);

// Read cookies
async fn protected_route(cookies: Cookies) -> Result<Response> {
    let username = cookies.get("session_user")
        .unwrap_or("anonymous".to_string());

    Ok(Response::text(format!("Welcome back, {}!", username)))
}

// Remove cookies
let response = Response::text("Logged out")
    .remove_cookie("session");
```

### **๐Ÿ›ก๏ธ Powerful Middleware System**

Composable middleware for authentication, logging, CORS, and more:

```rust
use ignitia::middleware::{AuthMiddleware, CorsMiddleware, LoggerMiddleware};

let router = Router::new()
    // Global middleware
    .middleware(LoggerMiddleware)
    .middleware(CorsMiddleware::new()
        .allow_origin("https://example.com"))

    // Protected routes
    .middleware(AuthMiddleware::new("secret-token")
        .protect_path("/api/admin")
        .protect_path("/dashboard"))

    .get("/api/admin/users", admin_users)
    .get("/dashboard", dashboard);
```

### **๐Ÿ” Authentication & Authorization**

Built-in session management and role-based access control:

```rust
// Custom authentication middleware
#[derive(Clone)]
struct AuthMiddleware {
    protected_paths: Vec<String>,
}

#[async_trait]
impl Middleware for AuthMiddleware {
    async fn before(&self, req: &mut Request) -> Result<()> {
        let path = req.uri.path();

        if self.protected_paths.iter().any(|p| path.starts_with(p)) {
            let _session = req.cookie("session")
                .ok_or_else(|| Error::Unauthorized)?;
            // Validate session...
        }

        Ok(())
    }
}
```

---

## ๐Ÿ”ง Middleware

### **Built-in Middleware**

| Middleware | Purpose | Usage |
|------------|---------|-------|
| `LoggerMiddleware` | Request/response logging | `.middleware(LoggerMiddleware)` |
| `CorsMiddleware` | Cross-origin resource sharing | `.middleware(CorsMiddleware::new())` |
| `AuthMiddleware` | Authentication | `.middleware(AuthMiddleware::new("token"))` |

### **Custom Middleware**

Create your own middleware by implementing the `Middleware` trait:

```rust
use ignitia::{Middleware, async_trait};

struct RateLimitMiddleware {
    max_requests: usize,
    window: Duration,
}

#[async_trait]
impl Middleware for RateLimitMiddleware {
    async fn before(&self, req: &mut Request) -> Result<()> {
        // Rate limiting logic
        Ok(())
    }

    async fn after(&self, res: &mut Response) -> Result<()> {
        // Add rate limit headers
        res.headers.insert(
            "X-RateLimit-Remaining",
            "99".parse().unwrap()
        );
        Ok(())
    }
}
```

---

## ๐Ÿช Cookie Management

### **Setting Cookies**

```rust
use ignitia::{Cookie, SameSite};

// Session cookie
let session = Cookie::new("session", "abc123")
    .path("/")
    .max_age(3600)
    .http_only()
    .same_site(SameSite::Lax);

// Persistent cookie
let preferences = Cookie::new("theme", "dark")
    .path("/")
    .max_age(86400 * 30) // 30 days
    .same_site(SameSite::Strict);

// Secure cookie
let secure_token = Cookie::new("csrf_token", "xyz789")
    .path("/")
    .secure()
    .http_only()
    .same_site(SameSite::Strict);

Response::text("Cookies set!")
    .add_cookie(session)
    .add_cookie(preferences)
    .add_cookie(secure_token)
```

### **Reading Cookies**

```rust
async fn handle_request(cookies: Cookies) -> Result<Response> {
    // Get all cookies
    let cookies = cookies;

    // Get specific cookie
    let session = cookies.get("session");

    // Check if cookie exists
    if cookies.contains("user_preferences") {
        // Handle with preferences
    }

    Response::json(cookies.all())
}
```

### **Cookie Security**

```rust
// Production-ready secure cookie
let secure_session = Cookie::new("session", session_id)
    .path("/")
    .max_age(3600)
    .http_only()        // Prevent XSS
    .secure()           // HTTPS only
    .same_site(SameSite::Strict); // CSRF protection
```

---

## ๐Ÿ” Authentication

### **Session-Based Authentication**

```rust
async fn login(req: Request) -> Result<Response> {
    let credentials: LoginForm = req.json()?;

    if validate_credentials(&credentials).await? {
        let session_token = generate_session_token();

        let session_cookie = Cookie::new("session", session_token)
            .path("/")
            .max_age(3600)
            .http_only()
            .same_site(SameSite::Lax);

        Ok(Response::json(serde_json::json!({
            "status": "success",
            "message": "Login successful"
        }))?.add_cookie(session_cookie))
    } else {
        Err(Error::Unauthorized)
    }
}

async fn logout(_req: Request) -> Result<Response> {
    Ok(Response::json(serde_json::json!({
        "status": "success",
        "message": "Logged out"
    }))?.remove_cookie("session"))
}
```

### **Protected Routes with Middleware**

```rust
let router = Router::new()
    .middleware(AuthMiddleware::new()
        .protect_paths(vec!["/dashboard", "/admin", "/api/protected"]))

    // These routes are automatically protected
    .get("/dashboard", dashboard)
    .get("/admin", admin_panel)
    .get("/api/protected/data", protected_data);
```

---

## ๐Ÿ“š Examples

Ignitia comes with comprehensive examples to get you started:

### **๐Ÿ  Basic Server**
```
cargo run --example basic_server
# http://127.0.0.1:3000
```
Demonstrates basic routing, JSON responses, and parameter extraction.

### **๐Ÿ” Authentication System**
```
cargo run --example login_example
# http://127.0.0.1:3008
```
Complete login/logout system with session management and protected routes.

### **๐Ÿ›ก๏ธ Middleware Showcase**
```
cargo run --example login_with_middleware_example
# http://127.0.0.1:3009
```
Advanced authentication using middleware with role-based access control.

### **๐Ÿช Cookie Management**
```
cargo run --example cookie_framework_example
# http://127.0.0.1:3006
```
Comprehensive cookie handling with security features and session management.

### **โšก Custom Middleware**
```
cargo run --example custom_middleware_example
# http://127.0.0.1:3004
```
Rate limiting, request validation, security headers, and custom middleware examples.

### **๐Ÿ“Š JSON API**
```
cargo run --example json_api
# http://127.0.0.1:3002
```
RESTful API for managing todos with in-memory storage and CRUD operations.

### **๐Ÿ“ File Server**
```
cargo run --example file_server
# http://127.0.0.1:3003
```
Static file server with security features, MIME type detection, and directory traversal protection.

### **๐ŸŽญ Middleware Demo**
```
cargo run --example middleware_example
# http://127.0.0.1:3001
```
CORS, authentication, and logging middleware examples.

---

## ๐Ÿ”Œ API Reference

### **Router**

| Method              | Description              |
|---------------------|--------------------------|
| `Router::new()`     | Create a new router      |
| `.get(path, handler)` | Add GET route            |
| `.post(path, handler)` | Add POST route           |
| `.put(path, handler)`  | Add PUT route            |
| `.delete(path, handler)` | Add DELETE route         |
| `.patch(path, handler)` | Add PATCH route          |
| `.middleware(middleware)` | Add middleware          |
| `.not_found(handler)`     | Set 404 handler          |

***

### **Request**

| Method                 | Description                   | Example                          |
|------------------------|-------------------------------|---------------------------------|
| `req.param(key)`       | Get route parameter            | `req.param("id")`               |
| `req.query(key)`       | Get query parameter            | `req.query("limit")`            |
| `req.header(key)`      | Get header value               | `req.header("User-Agent")`      |
| `req.json::<T>()`      | Parse JSON body into type `T` | `req.json::<User>()?`            |
| `req.cookies()`        | Get all cookies                | `req.cookies().all()`           |
| `req.cookie(key)`      | Get specific cookie            | `req.cookie("session")`         |

***

### **Extractors for Handler Functions**

| Extractor             | Description                                    | Example Usage                                   |
|-----------------------|------------------------------------------------|------------------------------------------------|
| `Path<T>`             | Extract typed route parameters                  | `async fn handler(Path(params): Path<(String, u32)>) { ... }` |
| `Query<T>`            | Extract typed query parameters                  | `async fn handler(Query(filter): Query<Filter>) { ... }`    |
| `Json<T>`             | Parse JSON request body into type `T`          | `async fn handler(Json(user): Json<User>) { ... }`           |
| `Body`                | Access raw request body as bytes                 | `async fn handler(Body(body): Body) { ... }`                 |
| `Extension<T>`        | Inject shared application state or dependencies | `async fn handler(Extension(state): Extension<AppState>) { ... }` |

***

### **Response**

| Method                   | Description                | Example                              |
|--------------------------|----------------------------|------------------------------------|
| `Response::text(content)` | Return plain text response | `Response::text("Hello")`           |
| `Response::html(content)` | Return HTML response       | `Response::html("<h1>Hi</h1>")`    |
| `Response::json(data)`    | Return JSON response       | `Response::json(user)?`              |
| `Response::not_found()`   | Return 404 Not Found       | `Response::not_found()`              |
| `.add_cookie(cookie)`     | Add cookie to response     | `.add_cookie(session)`               |
| `.remove_cookie(name)`    | Remove cookie from client  | `.remove_cookie("session")`         |

***

### **Cookie Builder**

| Method              | Description                     | Example                         |
|---------------------|---------------------------------|--------------------------------|
| `Cookie::new(name, value)` | Create a new cookie             | `Cookie::new("user", "john")`  |
| `.path(path)`       | Set cookie path                 | `.path("/")`                   |
| `.domain(domain)`   | Set cookie domain               | `.domain("example.com")`       |
| `.max_age(seconds)` | Set max age in seconds          | `.max_age(3600)`               |
| `.expires(time)`    | Set expiration time             | `.expires(SystemTime::now())`  |
| `.secure()`         | Mark cookie secure (HTTPS only) | `.secure()`                    |
| `.http_only()`      | Disallow JavaScript access      | `.http_only()`                 |
| `.same_site(policy)`| Set SameSite attribute          | `.same_site(SameSite::Lax)`   |

### **Middleware Trait**

```rust
#[async_trait]
pub trait Middleware: Send + Sync {
    async fn before(&self, req: &mut Request) -> Result<()> { Ok(()) }
    async fn after(&self, res: &mut Response) -> Result<()> { Ok(()) }
}
```

---


### **Test Your Application**

```
# Start server
cargo run --example basic_server &

# Test endpoints
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/users/123
curl -X POST -H "Content-Type: application/json" \
     -d '{"name":"John"}' \
     http://127.0.0.1:3000/api/data
```

---

## ๐ŸŽฏ Performance

### **Benchmarks**

- **Zero-copy**: Efficient request/response handling with minimal allocations
- **Async**: Built on Tokio for excellent concurrency
- **Lightweight**: ~50KB binary overhead
- **Fast compilation**: Small dependency tree for quick builds
- **Memory efficient**: Smart use of Arc and shared state

### **Performance Tips**

```
// Use connection pooling
let router = Router::new()
    .middleware(ConnectionPoolMiddleware::new())

    // Cache static responses
    .middleware(CacheMiddleware::new())

    // Compress responses
    .middleware(CompressionMiddleware::new());
```

---

## ๐Ÿ”’ Security Features

### **Built-in Security**

- โœ… **Path traversal protection** in static file serving
- โœ… **CORS middleware** for cross-origin requests
- โœ… **Authentication middleware** with configurable paths
- โœ… **Security headers middleware** (CSP, XSS protection, etc.)
- โœ… **Rate limiting middleware** to prevent abuse
- โœ… **Secure cookie attributes** (HttpOnly, Secure, SameSite)
- โœ… **Session management** with proper invalidation

### **Security Best Practices**

```rust
// Secure cookie configuration
let secure_cookie = Cookie::new("session", session_token)
    .path("/")
    .max_age(3600)
    .http_only()     // Prevent XSS
    .secure()        // HTTPS only in production
    .same_site(SameSite::Strict); // CSRF protection

// Security headers
let router = Router::new()
    .middleware(SecurityHeadersMiddleware::new()
        .csp("default-src 'self'")
        .hsts(31536000)
        .frame_deny());
```

---

## ๐Ÿ› ๏ธ Development

### **Project Structure**

```
ignitia/
โ”œโ”€โ”€ Cargo.toml
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ basic_server.rs
โ”‚   โ”œโ”€โ”€ login_example.rs
โ”‚   โ”œโ”€โ”€ cookie_framework.rs
โ”‚   โ”œโ”€โ”€ custom_middleware.rs
โ”‚   โ”œโ”€โ”€ login_with_middleware.rs
โ”‚   โ”œโ”€โ”€ middleware_example.rs
โ”‚   โ”œโ”€โ”€ json_api.rs
โ”‚   โ””โ”€โ”€ file_server.rs
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ lib.rs                  # Main library exports and re-exports
    โ”œโ”€โ”€ router/                 # Routing modules
    โ”‚   โ”œโ”€โ”€ mod.rs
    โ”‚   โ”œโ”€โ”€ route.rs
    โ”‚   โ””โ”€โ”€ method.rs
    โ”œโ”€โ”€ middleware/             # Middleware implementations
    โ”‚   โ”œโ”€โ”€ mod.rs
    โ”‚   โ”œโ”€โ”€ logger.rs
    โ”‚   โ”œโ”€โ”€ cors.rs
    โ”‚   โ””โ”€โ”€ auth.rs
    โ”œโ”€โ”€ request/                # Request handling components
    โ”‚   โ”œโ”€โ”€ mod.rs
    โ”‚   โ”œโ”€โ”€ body.rs
    โ”‚   โ””โ”€โ”€ params.rs
    โ”œโ”€โ”€ response/               # Response creation and builders
    โ”‚   โ”œโ”€โ”€ mod.rs
    โ”‚   โ”œโ”€โ”€ builder.rs
    โ”‚   โ””โ”€โ”€ status.rs
    โ”œโ”€โ”€ handler/                # Handler traits and extractors
    โ”‚   โ”œโ”€โ”€ mod.rs
    โ”‚   โ””โ”€โ”€ extractor.rs
    โ”œโ”€โ”€ server/                 # HTTP server implementation
    โ”‚   โ”œโ”€โ”€ mod.rs
    โ”‚   โ””โ”€โ”€ connection.rs
    โ”œโ”€โ”€ cookie/                 # Cookie management utilities
    โ”‚   โ””โ”€โ”€ mod.rs
    โ”œโ”€โ”€ extension/              # Extension types and utilities
    โ”‚   โ””โ”€โ”€ mod.rs
    โ”œโ”€โ”€ error/                  # Error types and handling
    โ”‚   โ””โ”€โ”€ mod.rs
    โ””โ”€โ”€ utils/                  # Helper utilities
        โ””โ”€โ”€ mod.rs
```

### **Building**

```
# Debug build
cargo build

# Release build (optimized)
cargo build --release

# Run all examples
cargo run --example basic_server
cargo run --example login_example
cargo run --example cookie_framework_example

# Check code quality
cargo fmt
cargo clippy
cargo test

# Generate documentation
cargo doc --open
```

---

## ๐Ÿค Contributing

We welcome contributions! Here's how you can help make Ignitia even better:

### **Ways to Contribute**

- ๐Ÿ› **Bug Reports**: Found a bug? Open an issue!
- โœจ **Feature Requests**: Have an idea? We'd love to hear it!
- ๐Ÿ“– **Documentation**: Help improve our docs
- ๐Ÿงช **Tests**: Add more test coverage
- ๐Ÿ”ง **Code**: Submit pull requests

### **Development Setup**

```
# Clone the repository
git clone https://github.com/AarambhDevHub/ignitia.git
cd ignitia

# Install dependencies and build
cargo build

# Run tests
cargo test --all

# Run examples
cargo run --example basic_server
```

### **Guidelines**

1. **Code Quality**: Run `cargo fmt` and `cargo clippy` before submitting
2. **Tests**: Add tests for new features
3. **Documentation**: Update README and add doc comments
4. **Examples**: Provide examples for new features
5. **Compatibility**: Ensure backward compatibility when possible

### **Pull Request Process**

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## ๐Ÿ“ Changelog

### **v0.1.2** - Initial Release ๐ŸŽ‰

#### **Core Features**
- โœ… Advanced routing with support for typed path parameters and wildcard routes
- โœ… Comprehensive middleware system with support for common and custom middleware
- โœ… Built-in secure cookie management with full attribute controls (HttpOnly, Secure, SameSite)
- โœ… Authentication and authorization middleware with path-based protection
- โœ… Static file serving with path traversal security protections
- โœ… JSON API support with automatic request body deserialization and response serialization
- โœ… Robust request/response handling with detailed error management and status codes

#### **Middleware**
- โœ… Authentication middleware supporting token and session validation with configurable protected paths
- โœ… CORS middleware with customizable allowed origins, methods, and headers
- โœ… Request logging middleware with HTTP version and status codes logging
- โœ… Rate limiting middleware for abuse prevention (custom middleware support)
- โœ… Security headers middleware for CSP, HSTS, frame options, and more (custom middleware support)
- โœ… Full support for user-defined custom middleware implementations via the Middleware trait

#### **Examples**
- โœ… Basic server demonstrating core routing and responses
- โœ… Complete authentication system with session management and role-based access control
- โœ… Cookie management showcase with secure cookie creation, reading, and removal
- โœ… Custom middleware examples including rate limiting and security headers
- โœ… JSON API example with CRUD operations and typed data handling
- โœ… Static file server example with MIME detection and security checks
- โœ… Middleware integration examples covering logging, CORS, and authentication

#### **Security**
- โœ… Secure cookie configurations (HttpOnly, Secure, SameSite)
- โœ… Path traversal protection in static file serving
- โœ… Session management with cookie-based authentication
- โœ… CSRF protection via SameSite cookie policies and middleware
- โœ… XSS prevention through secure cookie flags and content headers

---

## ๐Ÿ™ Acknowledgments

### **Built on Strong Foundations**

- **[Hyper]https://hyper.rs/** - High-performance HTTP implementation
- **[Tokio]https://tokio.rs/** - Asynchronous runtime for Rust
- **Community** - Inspired by frameworks like Actix-web, Warp, and Axum

### **Special Thanks**

- **Rust Community** - For creating an amazing ecosystem
- **Contributors** - Everyone who helps make ignitia better
- **Early Adopters** - Thanks for trying ignitia and providing feedback!

---


## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## โ˜• Support the Project
If you find this project helpful, consider buying me a coffee!
[Buy Me a Coffee](https://buymeacoffee.com/aarambhdevhub)


---

## ๐Ÿš€ Getting Started

Ready to ignitia your web development? Let's get started:

```
# Create a new project
cargo new my-ignitia-app
cd my-ignitia-app

# Add ignitia to Cargo.toml
echo '[dependencies]
ignitia = "0.1.2"
tokio = { version = "1.40", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"' >> Cargo.toml

# Create your first ignitia app
echo 'use ignitia::{Router, Server, Response, handler_fn};

#[tokio::main]
async fn main() -> ignitia::Result<()> {
    let router = Router::new()
        .get("/", handler_fn(|_| async {
            Ok(Response::html("<h1>๐Ÿ”ฅ Welcome to ignitia!</h1>"))
        }));

    let server = Server::new(router, "127.0.0.1:3000".parse().unwrap());
    println!("๐Ÿ”ฅ Server igniting on http://127.0.0.1:3000");
    server.ignitia().await.unwrap();
    Ok(())
}' > src/main.rs

# Run your app
cargo run
```

### **Next Steps**

1. ๐Ÿ“– **Explore Examples**: Check out our comprehensive examples
2. ๐Ÿ› ๏ธ **Build Something**: Create your first API or web app
3. ๐Ÿค **Join Community**: Connect with other ignitia developers
4. ๐Ÿ“บ **Learn More**: Subscribe to [Aarambh Dev Hub]https://youtube.com/@aarambhdevhub

---

<div align="center">

## ๐Ÿ”ฅ **Ignitia. Build. Deploy.** ๐Ÿ”ฅ

**Built with โค๏ธ by [Aarambh Dev Hub](https://youtube.com/@aarambhdevhub)**

*Where every line of code ignitias possibilities.*

[![YouTube](https://img.shields.io/badge/YouTube-Aarambh%20Dev%20Hub-red?style=for-the-badge&logo=youtube)](https://youtube.com/@aarambhdevhub)
[![GitHub](https://img.shields.io/badge/GitHub-ignitia-black?style=for-the-badge&logo=github)](https://github.com/AarambhDevHub/ignitia)
[![Crates.io](https://img.shields.io/badge/Crates.io-ignitia-orange?style=for-the-badge&logo=rust)](https://crates.io/crates/ignitia)

</div>