You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.rs 3.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. use std::env;
  2. use std::ffi::OsStr;
  3. use std::fs::{read_dir, File};
  4. use std::io::prelude::*;
  5. use std::io::{Error, ErrorKind};
  6. use std::path::PathBuf;
  7. use async_std::fs::read_to_string;
  8. use chrono::prelude::Local;
  9. use dotenv;
  10. use serde::{Deserialize, Serialize};
  11. use serde_json;
  12. use tera::{Context, Tera};
  13. use tide::utils::After;
  14. use tide::{Body, Response, StatusCode};
  15. use uuid::Uuid;
  16. #[derive(Debug, Serialize, Deserialize)]
  17. struct Post {
  18. id: String,
  19. title: String,
  20. body: String,
  21. date: String,
  22. }
  23. impl Post {
  24. fn save(&mut self) -> std::io::Result<()> {
  25. let mut path: PathBuf = get_posts_directory()?;
  26. let filename = format!("{}.json", self.id);
  27. path = path.join(&filename);
  28. let mut file = match File::create(&path) {
  29. Err(why) => panic!("couldn't create {}: {}", self.id, why),
  30. Ok(file) => file,
  31. };
  32. match file.write_all(serde_json::to_string(&self)?.as_bytes()) {
  33. Err(why) => Err(Error::new(
  34. ErrorKind::Other,
  35. format!("couldn't write to {}.json: {}", self.id, why),
  36. )),
  37. Ok(_) => Ok(()),
  38. }
  39. }
  40. }
  41. fn get_posts_directory() -> Result<PathBuf, Error> {
  42. match env::var("POSTS_DIR") {
  43. Ok(dir) => Ok(dir.into()),
  44. Err(_) => Err(Error::new(
  45. ErrorKind::Other,
  46. "Posts directory environment variable not set",
  47. )),
  48. }
  49. }
  50. async fn read_all_posts() -> Result<Vec<Post>, Error> {
  51. let path = get_posts_directory()?;
  52. let mut posts: Vec<Post> = vec![];
  53. for file in read_dir(path)? {
  54. let file = file?;
  55. if let Some("json") = file.path().extension().and_then(OsStr::to_str) {
  56. let contents = read_to_string(file.path()).await?;
  57. let mut post: Post = serde_json::from_str(&contents)?;
  58. post.body = post.body.replace("\n", "<br>");
  59. posts.push(post);
  60. }
  61. }
  62. Ok(posts)
  63. }
  64. #[async_std::main]
  65. async fn main() -> std::io::Result<()> {
  66. dotenv::dotenv().ok();
  67. tide::log::start();
  68. let mut app = tide::new();
  69. app.with(After(|mut res: Response| async {
  70. if let Some(err) = res.downcast_error::<async_std::io::Error>() {
  71. println!("{:?}", res);
  72. if let ErrorKind::NotFound = err.kind() {
  73. res.set_status(StatusCode::NotFound);
  74. }
  75. }
  76. Ok(res)
  77. }));
  78. app.with(After(|mut res: Response| async {
  79. res.set_content_type(tide::http::mime::HTML);
  80. Ok(res)
  81. }));
  82. app.at("/admin").get(|_| async {
  83. let tera = Tera::new("templates/**/*.html")?;
  84. let posts = read_all_posts().await?;
  85. let mut context = Context::new();
  86. context.insert("posts", &posts);
  87. let html = tera.render("admin/index.html", &context)?;
  88. Ok(Body::from_string(html))
  89. });
  90. app.at("/admin/posts")
  91. .post(|mut req: tide::Request<()>| async move {
  92. let mut post: Post = req.body_form().await?;
  93. post.id = Uuid::new_v4().to_string();
  94. post.date = Local::now().date().naive_local().to_string();
  95. post.body = post.body.trim().to_owned();
  96. post.save()?;
  97. Ok(tide::Redirect::new("/admin"))
  98. });
  99. app.listen("127.0.0.1:8080").await?;
  100. Ok(())
  101. }