1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use axum::http::StatusCode;
use axum::response::IntoResponse;

/// Handle for not found and return 404
/// # Global handle not found Example
///
/// ```rust,no_run
/// use axum::{Router, routing::get, ServiceExt};
/// use axum_restful::utils::handle_not_found;
///
/// let app = Router::new()
///     .route("/", get(|| async { "Hello world!"}))
///     .fallback(handle_not_found);
/// # async {
///     let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
///     axum::serve(listener, app.into_make_service()).await.unwrap();
/// # };
/// ```
pub async fn handle_not_found() -> impl IntoResponse {
    (StatusCode::NOT_FOUND, "nothing to see here")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::*;
    use axum::{routing::get, Router};

    #[tokio::test]
    async fn handle_404() {
        let app = Router::new()
            .route("/", get(|| async { "Hello" }))
            .fallback(handle_not_found);
        let client = TestClient::new(app);
        let res = client.get("/").send().await;
        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.text().await, "Hello".to_owned());

        let res = client.get("/test").send().await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }
}