Skip to content

Commit

Permalink
implement NotFoundCatcher (#105)
Browse files Browse the repository at this point in the history
* implement NotFoundCatcher

* fix clippy warnings

* fix clippy warnings
  • Loading branch information
prabirshrestha authored Sep 12, 2022
1 parent d7e1eb0 commit ee4da21
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/routes/posts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub async fn get_posts(depot: &mut Depot, res: &mut Response) -> Result<()> {
.map(|key| blog.get_post(key).unwrap())
.collect();

render_html(res, |o| templates::posts_html(o, &blog, &posts))?;
render_html(res, |o| templates::posts_html(o, blog, &posts))?;

Ok(())
}
Expand Down
22 changes: 19 additions & 3 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{appstate::AppState, routes};
use crate::{appstate::AppState, render_html, routes, templates};
use anyhow::Result;
use listenfd::ListenFd;
use salvo::{extra, prelude::*};
use salvo::{extra, prelude::*, Catcher};
use std::net::SocketAddr;

pub async fn run() -> Result<()> {
Expand Down Expand Up @@ -40,5 +40,21 @@ async fn make_service() -> Result<Service> {
.push(Router::with_path("/rss").get(routes::rss::rss_feed))
.push(Router::with_path("/healthcheck").get(routes::health_check))
.push(Router::with_path("/robots.txt").get(routes::robots_txt));
Ok(Service::new(router))
let catchers: Vec<Box<dyn Catcher>> = vec![Box::new(NotFoundCatcher)];
Ok(Service::new(router).with_catchers(catchers))
}

struct NotFoundCatcher;

impl Catcher for NotFoundCatcher {
fn catch(&self, _req: &Request, _depot: &Depot, res: &mut Response) -> bool {
if let Some(StatusCode::NOT_FOUND) = res.status_code() {
match render_html(res, |o| templates::notfound(o)) {
Ok(_) => true,
Err(_) => false,
}
} else {
false
}
}
}
14 changes: 11 additions & 3 deletions templates/notfound.rs.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
@use super::statics::*;
@()
<!DOCTYPE html>
<html lang="en">
Expand All @@ -7,9 +8,16 @@
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title>404 Not Found</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono">
<link rel="stylesheet" type="text/css" href="/static/@style_css.name"/>
</head>
<body>
<h1>404 Not Found</h1>
<p><a href="/">Homepage</a></p>
<body class="notfound">
<main>
<header class="article">Uh oh...</header>
<article>
We can't find the page you are looking for.
<p><a href="/">Go to homepage</a></p>
</article>
</main>
</body>
</html>

0 comments on commit ee4da21

Please sign in to comment.