custom_404/
custom_404.rs

1extern crate ferrum;
2extern crate ferrum_router;
3
4// To run, $ cargo run --example custom_404
5// To use, go to http://localhost:3000/foobar to see the custom 404
6// Or, go to http://localhost:3000 for a standard 200 OK
7
8use ferrum::{AfterMiddleware, Chain, Ferrum, FerrumError, FerrumResult, mime, Request, Response, StatusCode};
9use ferrum_router::{Router, NoRoute};
10
11struct Custom404;
12
13impl AfterMiddleware for Custom404 {
14    fn catch(&self, _: &mut Request, error: FerrumError) -> FerrumResult<Response> {
15        println!("Hitting custom 404 middleware");
16
17        if error.error.is::<NoRoute>() {
18            Ok(Response::new()
19                .with_content("Custom 404 response", mime::TEXT_PLAIN)
20                .with_status(StatusCode::NotFound))
21        } else {
22            Err(error)
23        }
24    }
25}
26
27fn main() {
28    let mut router = Router::new();
29    router.get("/", handler, None);
30
31    let mut chain = Chain::new(router);
32    chain.link_after(Custom404);
33
34    Ferrum::new(chain).http("localhost:3000").unwrap();
35}
36
37fn handler(_: &mut Request) -> FerrumResult<Response> {
38    Ok(Response::new().with_content("Handling response", mime::TEXT_PLAIN))
39}