rustmvc 0.2.2

A lightweight MVC framework for Rust
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
//! # RustMVC
//!
//! A lightweight MVC framework for Rust, built on top of Actix Web and Askama templates.
//! Provides routing, middlewares, request context, and response handling.
use actix_web::http::header::HeaderMap;
use actix_web::http::{Method, StatusCode};
use actix_web::web::Bytes;
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
pub use askama;
pub use askama::Template;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
pub mod authentication;

/// Shared pointer to a type implementing the `RenderModel` trait.
pub type ArcRenderModel = Arc<dyn RenderModel>;

/// Contains information about an incoming HTTP request.
#[derive(Clone)]
pub struct RequestContext {
    /// Query parameters from the URL (e.g., `/path?foo=bar` -> `{"foo": "bar"}`)
    pub params: HashMap<String, String>,
    /// Path parameters from the URL (e.g., `/profile/{username} -> /profile/lorenzo `)
    pub path_params: HashMap<String, String>,
    /// HTTP headers of the request
    pub headers: HeaderMap,
    /// The path of the request (e.g., `/about`)
    pub path: String,
    /// Request body bytes (useful for POST/PUT requests)
    pub body: Vec<u8>,
    ///Http Method
    pub method: HttpMethod,
    /// Rules that are set for the path
    pub rules: Vec<RouteRules>,
    /// User context
    pub user: Option<User>,
}
///User context
#[derive(Clone)]
pub struct User {
    pub name: String,
    pub roles: Vec<String>,
}
/// Represents the possible responses an action can return.
#[derive(Clone)]
pub enum ActionResult {
    /// HTML content as a raw string
    Html(String),
    /// Render a model implementing `RenderModel` (e.g., Askama templates)
    View(ArcRenderModel),
    /// Redirect to another URL
    Redirect(String),
    /// Return a static file (served from `wwwroot`)
    File(String),
    /// 404 Not Found
    NotFound,
    /// Pay Load Too Large
    PayloadTooLarge(String),
    /// UnAuthorized
    UnAuthorized(String),
    /// Forbidden
    Forbidden(String),
    /// Ok
    Ok(String),
    /// BadRequest
    BadRequest(String),
    /// Return Status Code with Body
    StatusCode(u16, String),
}
/// Trait implemented by models that can render themselves to HTML.
pub trait RenderModel: Send + Sync {
    /// Render the model into an HTML string
    fn render_html(&self) -> Result<String, askama::Error>;
}

/// Implemented for any Askama Template
impl<T: askama::Template + Send + Sync> RenderModel for T {
    fn render_html(&self) -> Result<String, askama::Error> {
        self.render()
    }
}

/// Type of an action function (controller handler)
pub type ActionFn = Arc<dyn Fn(RequestContext) -> ActionResult + Send + Sync + 'static>;

/// Type of a middleware function
pub type MiddlewareFn =
    Arc<dyn Fn(RequestContext, ActionFn) -> ActionResult + Send + Sync + 'static>;
///Rules for a route to pass before proceeding to action
#[derive(Clone, PartialEq, Eq)]
pub enum RouteRules {
    Authorize,
    AllowAnonymous,
    Roles(Vec<String>),
    RequestSizeLimit(usize),
}
/// Http Methods
#[derive(Clone, PartialEq)]
pub enum HttpMethod {
    GET,
    POST,
    PUT,
    DELETE,
    PATCH,
    OPTIONS,
    HEAD,
    TRACE,
    CONNECT,
    NotSupported,
}

/// Represents a route in the server
#[derive(Clone)]
pub struct Route {
    /// The path to match (e.g., `/about`)
    pub path: String,
    /// The action to execute when the route is matched
    pub action: ActionFn,
    /// Route Rules
    pub rules: Vec<RouteRules>,
    /// Http Method
    pub method: HttpMethod,
}
/// The main server struct of RustMVC.
///
/// Holds all the registered routes and middlewares.
/// Users create a `Server`, register routes and middlewares, and then start it.
pub struct Server {
    /// A vector of registered routes.
    /// Each route has a path and an action function.
    routes: Vec<Route>,
    /// A vector of middlewares.
    /// Middlewares are functions that wrap around route execution,
    /// allowing logging, authentication, request modification, etc.
    middlewares: Vec<MiddlewareFn>,
}

impl Server {
    /// Creates a new instance of the server with default logging middleware
    ///
    /// Example:
    /// ```rust
    /// let server = rustmvc::Server::new();
    /// ```
    pub fn new() -> Self {
        let mut server = Self {
            routes: Vec::new(),
            middlewares: Vec::new(),
        };
        // Default logging middleware
        server.add_middleware(|ctx, next| {
            println!("--- Incoming Request ---");
            println!("Path: {}", ctx.path);
            println!("Query Params: {:?}", ctx.params);
            println!("Headers:");
            for (key, value) in ctx.headers.iter() {
                println!("  {}: {:?}", key, value);
            }
            println!("------------------------");

            let result = next(ctx.clone());

            match &result {
                ActionResult::Html(_) => println!("Response: Html"),
                ActionResult::View(_) => println!("Response: View"),
                ActionResult::Redirect(url) => println!("Response: Redirect to {:?}", url),
                ActionResult::File(path) => println!("Response: File {:?}", path),
                ActionResult::NotFound => println!("Response: NotFound"),
                ActionResult::PayloadTooLarge(content) => println!("Response: {:?}", content),
                ActionResult::Forbidden(content) => println!("Response: {:?}", content),
                ActionResult::UnAuthorized(content) => println!("Response: {:?}", content),
                ActionResult::Ok(content) => println!("Response: {:?}", content),
                ActionResult::BadRequest(content) => println!("Response: {:?}", content),
                ActionResult::StatusCode(code, body) => println!("Response: {:?} {:?}", code, body),
            }
            println!("--- End of Request ---\n");

            result
        });

        server
    }
    fn match_and_extract_params(pattern: &str, path: &str) -> Option<HashMap<String, String>> {
        let pattern_segments: Vec<&str> = pattern.split('/').collect();
        let path_segments: Vec<&str> = path.split('/').collect();

        if pattern_segments.len() != path_segments.len() {
            return None;
        }

        let mut params = HashMap::new();

        for (p_segment, r_segment) in pattern_segments.iter().zip(path_segments.iter()) {
            if p_segment.starts_with('{') && p_segment.ends_with('}') {
                // This is a dynamic parameter, extract the key and value
                let key = p_segment.trim_matches(|c| c == '{' || c == '}').to_string();
                params.insert(key, r_segment.to_string());
            } else if p_segment != r_segment {
                // Static segments must match exactly
                return None;
            }
        }

        Some(params)
    }
    /// Add a middleware to the server
    ///
    /// Middlewares are executed in the order they are added.
    ///
    /// # Example
    /// ```rust
    /// server.add_middleware(|ctx, next| {
    ///     println!("Logging request: {}", ctx.path);
    ///     next(ctx)
    /// });
    /// ```
    pub fn add_middleware<F>(&mut self, mw: F)
    where
        F: Fn(RequestContext, ActionFn) -> ActionResult + Send + Sync + 'static,
    {
        self.middlewares.push(Arc::new(mw));
    }

    /// Add a static files middleware.
    /// By default it uses 'wwwroot' folder
    pub fn use_static_files(&mut self) {
        let middleware = move |ctx: RequestContext, next: ActionFn| {
            if ctx.method == HttpMethod::GET && ctx.path.contains('.') {
                return ActionResult::File(ctx.path);
            }

            next(ctx)
        };

        self.add_middleware(middleware);
    }
    /// Register a route that only responds to HTTP GET requests.
    pub fn get<F>(&mut self, path: &str, action: F, rules: Vec<RouteRules>)
    where
        F: Fn(RequestContext) -> ActionResult + Send + Sync + 'static,
    {
        self.add_route(path, action, HttpMethod::GET, rules);
    }

    /// Register a route that only responds to HTTP POST requests.
    pub fn post<F>(&mut self, path: &str, action: F, rules: Vec<RouteRules>)
    where
        F: Fn(RequestContext) -> ActionResult + Send + Sync + 'static,
    {
        self.add_route(path, action, HttpMethod::POST, rules);
    }

    /// Register a route that only responds to HTTP PUT requests.
    pub fn put<F>(&mut self, path: &str, action: F, rules: Vec<RouteRules>)
    where
        F: Fn(RequestContext) -> ActionResult + Send + Sync + 'static,
    {
        self.add_route(path, action, HttpMethod::PUT, rules);
    }

    /// Register a route that only responds to HTTP DELETE requests.
    pub fn delete<F>(&mut self, path: &str, action: F, rules: Vec<RouteRules>)
    where
        F: Fn(RequestContext) -> ActionResult + Send + Sync + 'static,
    {
        self.add_route(path, action, HttpMethod::DELETE, rules);
    }
    /// Register a route with the server
    ///
    /// # Example
    /// ```rust
    /// server.add_route("/", HomeController::index);
    /// ```
    pub fn add_route<F>(
        &mut self,
        path: &str,
        action: F,
        method: HttpMethod,
        rules: Vec<RouteRules>,
    ) where
        F: Fn(RequestContext) -> ActionResult + Send + Sync + 'static,
    {
        self.routes.push(Route {
            path: path.to_string(),
            action: Arc::new(action),
            method,
            rules,
        });
    }
    /// Internal function to handle an incoming request
    fn handle_request(&self, ctx: RequestContext) -> ActionResult {
        let routes = self.routes.clone();
        let route_handler: ActionFn = Arc::new(move |mut ctx: RequestContext| {
            for route in routes.iter() {
                if route.method != ctx.method {
                    continue;
                }
                if let Some(path_params) = Server::match_and_extract_params(&route.path, &ctx.path)
                {
                    ctx.path_params = path_params;

                    for rule in route.rules.clone() {
                        if let RouteRules::RequestSizeLimit(limit) = rule {
                            if ctx.body.len() > limit {
                                return ActionResult::PayloadTooLarge(format!(
                                    "Request to route '{}' exceeded the allowed size: {} bytes",
                                    route.path, limit
                                ));
                            }
                        } else if let RouteRules::Roles(roles) = rule {
                            match &ctx.user {
                                Some(user) => {
                                    let has_role = roles.iter().any(|r| user.roles.contains(r));
                                    if !has_role {
                                        return ActionResult::UnAuthorized(
                                            "You do not have the required role(s)".into(),
                                        );
                                    }
                                }
                                None => (),
                            }
                        }
                    }

                    // Execute the action with the modified context
                    return (route.action)(ctx);
                }
            }
            ActionResult::NotFound
        });

        let mut next = route_handler;
        for mw in self.middlewares.iter().rev() {
            let current_next = next.clone();
            let mw_clone = mw.clone();
            next = Arc::new(move |ctx: RequestContext| mw_clone(ctx, current_next.clone()));
        }
        next(ctx)
    }
    /// Start the server asynchronously
    ///
    /// # Example
    /// ```rust
    /// actix_web::rt::System::new().block_on(async {
    ///     server.start("127.0.0.1:8080").await.unwrap();
    /// });
    /// ```
    pub async fn start(self, addr: &str) -> std::io::Result<()> {
        println!("Server listening at http://{}", addr);
        let shared_routes = web::Data::new(self);

        HttpServer::new(move || {
            App::new()
                .app_data(shared_routes.clone())
                .default_service(web::to(
                    |req: HttpRequest, body: Bytes, srv: web::Data<Server>| {
                        let mut params = HashMap::new();
                        for (key, value) in req
                            .query_string()
                            .split('&')
                            .filter(|s| !s.is_empty())
                            .map(|pair| {
                                let mut kv = pair.splitn(2, '=');
                                (kv.next().unwrap_or(""), kv.next().unwrap_or(""))
                            })
                        {
                            params.insert(key.to_string(), value.to_string());
                        }

                        let mapped_methods = match req.method() {
                            &Method::GET => HttpMethod::GET,
                            &Method::POST => HttpMethod::POST,
                            &Method::PUT => HttpMethod::PUT,
                            &Method::DELETE => HttpMethod::DELETE,
                            &Method::PATCH => HttpMethod::PATCH,
                            &Method::CONNECT => HttpMethod::CONNECT,
                            &Method::OPTIONS => HttpMethod::OPTIONS,
                            &Method::HEAD => HttpMethod::HEAD,
                            &Method::TRACE => HttpMethod::TRACE,
                            _ => HttpMethod::NotSupported,
                        };

                        let route_rules = match srv.routes.iter().find(|r| {
                            r.path == req.path().to_string() && r.method == mapped_methods
                        }) {
                            Some(r) => r.rules.clone(),
                            None => Vec::new(),
                        };

                        let ctx = RequestContext {
                            path: req.path().to_string(),
                            headers: req.headers().clone(),
                            params,
                            path_params: HashMap::new(),
                            body: body.to_vec(),
                            method: mapped_methods,
                            rules: route_rules,
                            user: None,
                        };

                        let result = srv.handle_request(ctx);

                        let body = match result {
                            ActionResult::Html(s) => {
                                HttpResponse::Ok().content_type("text/html").body(s)
                            }
                            ActionResult::StatusCode(code, body) => {
                                let valid_code = StatusCode::from_u16(code)
                                    .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                                HttpResponse::build(valid_code)
                                    .content_type("application/json")
                                    .body(body)
                            }

                            ActionResult::View(renderer_arc) => match renderer_arc.render_html() {
                                Ok(html) => HttpResponse::Ok().content_type("text/html").body(html),
                                Err(e) => {
                                    eprintln!("Askama Rendering Error: {}", e);
                                    HttpResponse::InternalServerError()
                                        .content_type("application/json")
                                        .body(format!("Template Rendering Error: {}", e))
                                }
                            },
                            ActionResult::Ok(content) => HttpResponse::Ok()
                                .content_type("application/json")
                                .body(content),
                            ActionResult::BadRequest(content) => HttpResponse::BadRequest()
                                .content_type("application/json")
                                .body(content),
                            ActionResult::Redirect(url) => HttpResponse::Found()
                                .append_header(("Location", url))
                                .finish(),
                            ActionResult::File(path) => {
                                let wwwroot = std::env::current_dir()
                                    .unwrap()
                                    .join("wwwroot")
                                    .canonicalize()
                                    .unwrap();
                                let requested = Path::new(path.trim_start_matches(['/', '\\']));
                                let file_path = wwwroot.join(requested).canonicalize();

                                println!("wwwroot: {}", wwwroot.display());
                                println!("requested path: {:?}", requested);
                                println!("file_path: {:?}", file_path);

                                match file_path {
                                    Ok(path) if path.starts_with(&wwwroot) => {
                                        match std::fs::read(&path) {
                                            Ok(bytes) => {
                                                let content_type = mime_guess::from_path(&path)
                                                    .first_or_octet_stream();
                                                HttpResponse::Ok()
                                                    .content_type(content_type.as_ref())
                                                    .body(bytes)
                                            }
                                            Err(_) => HttpResponse::NotFound().body("Not found"),
                                        }
                                    }
                                    _ => HttpResponse::Forbidden().body("Access denied"),
                                }
                            }
                            ActionResult::PayloadTooLarge(body) => HttpResponse::PayloadTooLarge()
                                .content_type("application/json")
                                .body(body),

                            ActionResult::Forbidden(body) => HttpResponse::Forbidden()
                                .content_type("application/json")
                                .body(body),
                            ActionResult::UnAuthorized(body) => HttpResponse::Unauthorized()
                                .content_type("application/json")
                                .body(body),
                            ActionResult::NotFound => HttpResponse::NotFound()
                                .content_type("application/json")
                                .body("Not found"),
                        };

                        async move { body }
                    },
                ))
        })
        .bind(addr)?
        .run()
        .await
    }
}