|
@@ -1,10 +1,11 @@
|
1
|
1
|
use std::env;
|
2
|
|
-use std::fs::File;
|
|
2
|
+use std::fs::{read_dir, File};
|
3
|
3
|
use std::io::prelude::*;
|
4
|
4
|
use std::io::{Error, ErrorKind};
|
5
|
5
|
use std::path::PathBuf;
|
6
|
6
|
|
7
|
|
-use chrono::prelude::{Local, NaiveDate};
|
|
7
|
+use async_std::fs::read_to_string;
|
|
8
|
+use chrono::prelude::Local;
|
8
|
9
|
use dotenv;
|
9
|
10
|
use serde::{Deserialize, Serialize};
|
10
|
11
|
use serde_json;
|
|
@@ -40,7 +41,7 @@ impl Post {
|
40
|
41
|
}
|
41
|
42
|
}
|
42
|
43
|
|
43
|
|
-fn get_posts_directory() -> Result<PathBuf, std::io::Error> {
|
|
44
|
+fn get_posts_directory() -> Result<PathBuf, Error> {
|
44
|
45
|
match env::var("POSTS_DIR") {
|
45
|
46
|
Ok(dir) => Ok(dir.into()),
|
46
|
47
|
Err(_) => Err(Error::new(
|
|
@@ -50,6 +51,20 @@ fn get_posts_directory() -> Result<PathBuf, std::io::Error> {
|
50
|
51
|
}
|
51
|
52
|
}
|
52
|
53
|
|
|
54
|
+async fn read_all_posts() -> Result<Vec<Post>, Error> {
|
|
55
|
+ let path = get_posts_directory()?;
|
|
56
|
+ let mut posts: Vec<Post> = vec![];
|
|
57
|
+
|
|
58
|
+ for file in read_dir(path)? {
|
|
59
|
+ let file = file?;
|
|
60
|
+ let contents = read_to_string(file.path()).await?;
|
|
61
|
+ let post: Post = serde_json::from_str(&contents)?;
|
|
62
|
+ posts.push(post);
|
|
63
|
+ }
|
|
64
|
+
|
|
65
|
+ Ok(posts)
|
|
66
|
+}
|
|
67
|
+
|
53
|
68
|
#[async_std::main]
|
54
|
69
|
async fn main() -> std::io::Result<()> {
|
55
|
70
|
dotenv::dotenv().ok();
|
|
@@ -74,7 +89,10 @@ async fn main() -> std::io::Result<()> {
|
74
|
89
|
|
75
|
90
|
app.at("/admin").get(|_| async {
|
76
|
91
|
let tera = Tera::new("templates/**/*.html")?;
|
77
|
|
- let html = tera.render("admin/index.html", &Context::new())?;
|
|
92
|
+ let posts = read_all_posts().await?;
|
|
93
|
+ let mut context = Context::new();
|
|
94
|
+ context.insert("posts", &posts);
|
|
95
|
+ let html = tera.render("admin/index.html", &context)?;
|
78
|
96
|
Ok(Body::from_string(html))
|
79
|
97
|
});
|
80
|
98
|
|