您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

main.rs 2.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 tera::Context;
  9. use tide::utils::After;
  10. use tide::{Response, StatusCode};
  11. mod fs;
  12. mod routes;
  13. #[derive(Debug, Serialize, Deserialize)]
  14. pub struct Post {
  15. id: String,
  16. title: String,
  17. body: String,
  18. date: String,
  19. }
  20. impl Post {
  21. async fn save(&mut self) -> std::io::Result<()> {
  22. let mut path: PathBuf = fs::get_posts_directory_path().await?;
  23. let filename = format!("{}.json", self.id);
  24. path = path.join(&filename);
  25. let mut file = File::create(&path)?;
  26. file.write_all(serde_json::to_string(&self)?.as_bytes())?;
  27. Ok(())
  28. }
  29. fn from_str(blob: &str) -> Result<Post, Error> {
  30. let mut post: Post = match serde_json::from_str(blob) {
  31. Ok(p) => Ok(p),
  32. Err(_) => Err(Error::new(
  33. ErrorKind::Other,
  34. format!("Error deserializing post"),
  35. )),
  36. }?;
  37. post.body = post.body.replace("\n", "<br>");
  38. Ok(post)
  39. }
  40. }
  41. #[async_std::main]
  42. async fn main() -> std::io::Result<()> {
  43. dotenv::dotenv().ok();
  44. tide::log::start();
  45. let mut app = tide::new();
  46. app.with(After(|mut res: Response| async {
  47. let mut context = Context::new();
  48. match res.downcast_error::<async_std::io::Error>() {
  49. Some(e) => {
  50. context.insert("error", &e.to_string());
  51. let status = if let ErrorKind::NotFound = e.kind() {
  52. StatusCode::NotFound
  53. } else {
  54. StatusCode::InternalServerError
  55. };
  56. res.set_body(routes::render_template("error.html", &context)?);
  57. res.set_status(status);
  58. }
  59. None => match res.status() {
  60. StatusCode::NotFound => {
  61. context.insert("error", "Page not found");
  62. res.set_body(routes::render_template("error.html", &context)?);
  63. }
  64. _ => {}
  65. },
  66. };
  67. Ok(res)
  68. }));
  69. app.with(After(|mut res: Response| async {
  70. res.set_content_type(tide::http::mime::HTML);
  71. Ok(res)
  72. }));
  73. app.with(tide::sessions::SessionMiddleware::new(
  74. tide::sessions::MemoryStore::new(),
  75. std::env::var("TIDE_SECRET")
  76. .expect(
  77. "Please provide a TIDE_SECRET value of at \
  78. least 32 bytes in order to run this example",
  79. )
  80. .as_bytes(),
  81. ));
  82. app.at("/").get(routes::index);
  83. app.at("/posts").post(routes::create_post);
  84. app.at("/posts/:id").get(routes::single_post);
  85. app.at("/posts/:id/edit").get(routes::edit_post);
  86. app.at("/login").get(routes::login_page).post(routes::login);
  87. app.at("/logout").post(routes::logout);
  88. app.listen("127.0.0.1:8080").await?;
  89. Ok(())
  90. }