Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

middleware.rs 1.4KB

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