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 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use std::fs::File;
  2. use std::io::prelude::*;
  3. use std::io::{Error, ErrorKind};
  4. use std::path::PathBuf;
  5. use dotenv;
  6. use serde::{Deserialize, Serialize};
  7. use serde_json;
  8. use tide::utils::After;
  9. mod fs;
  10. mod middleware;
  11. mod routes;
  12. #[derive(Debug, Serialize, Deserialize)]
  13. pub struct Post {
  14. id: String,
  15. title: String,
  16. body: String,
  17. date: String,
  18. }
  19. impl Post {
  20. async fn save(&mut self) -> std::io::Result<()> {
  21. let mut path: PathBuf = fs::get_posts_directory_path().await?;
  22. let filename = format!("{}.json", self.id);
  23. path = path.join(&filename);
  24. let mut file = File::create(&path)?;
  25. file.write_all(serde_json::to_string(&self)?.as_bytes())?;
  26. Ok(())
  27. }
  28. fn from_str(blob: &str) -> Result<Post, Error> {
  29. let mut post: Post = match serde_json::from_str(blob) {
  30. Ok(p) => Ok(p),
  31. Err(_) => Err(Error::new(
  32. ErrorKind::Other,
  33. format!("Error deserializing post"),
  34. )),
  35. }?;
  36. post.body = post.body.replace("\n", "<br>");
  37. Ok(post)
  38. }
  39. }
  40. #[async_std::main]
  41. async fn main() -> std::io::Result<()> {
  42. dotenv::dotenv().ok();
  43. tide::log::start();
  44. let mut app = tide::new();
  45. app.with(After(middleware::errors));
  46. app.with(middleware::session());
  47. app.at("/").get(routes::index);
  48. app.at("/posts").post(routes::create_post);
  49. app.at("/posts/:id").get(routes::single_post);
  50. app.at("/posts/:id/edit").get(routes::edit_post);
  51. app.at("/login").get(routes::login_page).post(routes::login);
  52. app.at("/logout").post(routes::logout);
  53. app.listen("127.0.0.1:8080").await?;
  54. Ok(())
  55. }