Browse Source

Move middleware to module

master
Dylan Baker 3 years ago
parent
commit
7835713620
2 changed files with 53 additions and 42 deletions
  1. 3
    42
      src/main.rs
  2. 50
    0
      src/middleware.rs

+ 3
- 42
src/main.rs View File

@@ -6,11 +6,10 @@ use std::path::PathBuf;
6 6
 use dotenv;
7 7
 use serde::{Deserialize, Serialize};
8 8
 use serde_json;
9
-use tera::Context;
10 9
 use tide::utils::After;
11
-use tide::{Response, StatusCode};
12 10
 
13 11
 mod fs;
12
+mod middleware;
14 13
 mod routes;
15 14
 
16 15
 #[derive(Debug, Serialize, Deserialize)]
@@ -50,46 +49,8 @@ async fn main() -> std::io::Result<()> {
50 49
     tide::log::start();
51 50
     let mut app = tide::new();
52 51
 
53
-    app.with(After(|mut res: Response| async {
54
-        let mut context = Context::new();
55
-
56
-        match res.downcast_error::<async_std::io::Error>() {
57
-            Some(e) => {
58
-                context.insert("error", &e.to_string());
59
-                let status = if let ErrorKind::NotFound = e.kind() {
60
-                    StatusCode::NotFound
61
-                } else {
62
-                    StatusCode::InternalServerError
63
-                };
64
-                res.set_body(routes::render_template("error.html", &context)?);
65
-                res.set_status(status);
66
-            }
67
-            None => match res.status() {
68
-                StatusCode::NotFound => {
69
-                    context.insert("error", "Page not found");
70
-                    res.set_body(routes::render_template("error.html", &context)?);
71
-                }
72
-                _ => {}
73
-            },
74
-        };
75
-
76
-        Ok(res)
77
-    }));
78
-
79
-    app.with(After(|mut res: Response| async {
80
-        res.set_content_type(tide::http::mime::HTML);
81
-        Ok(res)
82
-    }));
83
-
84
-    app.with(tide::sessions::SessionMiddleware::new(
85
-        tide::sessions::MemoryStore::new(),
86
-        std::env::var("TIDE_SECRET")
87
-            .expect(
88
-                "Please provide a TIDE_SECRET value of at \
89
-                      least 32 bytes in order to run this example",
90
-            )
91
-            .as_bytes(),
92
-    ));
52
+    app.with(After(middleware::errors));
53
+    app.with(middleware::session());
93 54
 
94 55
     app.at("/").get(routes::index);
95 56
     app.at("/posts").post(routes::create_post);

+ 50
- 0
src/middleware.rs View File

@@ -0,0 +1,50 @@
1
+use tide::{
2
+    http::mime,
3
+    sessions::{CookieStore, SessionMiddleware},
4
+    Response, Result, StatusCode,
5
+};
6
+
7
+use std::{env, io::ErrorKind};
8
+use tera::Context;
9
+
10
+use crate::routes;
11
+
12
+pub fn session() -> SessionMiddleware<CookieStore> {
13
+    SessionMiddleware::new(
14
+        CookieStore::new(),
15
+        env::var("TIDE_SECRET")
16
+            .expect(
17
+                "Please provide a TIDE_SECRET value of at \
18
+                      least 32 bytes in order to run this example",
19
+            )
20
+            .as_bytes(),
21
+    )
22
+}
23
+
24
+pub async fn errors(mut res: Response) -> Result<Response> {
25
+    let mut context = Context::new();
26
+
27
+    match res.downcast_error::<async_std::io::Error>() {
28
+        Some(e) => {
29
+            context.insert("error", &e.to_string());
30
+            let status = if let ErrorKind::NotFound = e.kind() {
31
+                StatusCode::NotFound
32
+            } else {
33
+                StatusCode::InternalServerError
34
+            };
35
+            let body: String = routes::render_template("error.html", &context)?;
36
+            res.set_body(body);
37
+            res.set_status(status);
38
+        }
39
+        None => match res.status() {
40
+            StatusCode::NotFound => {
41
+                context.insert("error", "Page not found");
42
+                res.set_body(routes::render_template("error.html", &context)?);
43
+            }
44
+            _ => {}
45
+        },
46
+    };
47
+
48
+    res.set_content_type(mime::HTML);
49
+    Ok(res)
50
+}

Loading…
Cancel
Save