From a82e43ce7f76254eced8079f5bd01e633ffd9bfd Mon Sep 17 00:00:00 2001 From: Florian Briand Date: Sun, 4 Aug 2024 18:34:42 +0200 Subject: [PATCH] refacto: nest axum templates routes --- crates/app/src/lib.rs | 25 +++++++++++++------------ crates/app/src/templates/hello.rs | 15 ++++++++++++++- crates/app/src/templates/index.rs | 5 ----- crates/app/src/templates/mod.rs | 10 ++++++++-- 4 files changed, 35 insertions(+), 20 deletions(-) delete mode 100644 crates/app/src/templates/index.rs diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index cb78fca..e7ac668 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -2,26 +2,27 @@ mod templates; use std::path::Path; +use askama::Template; use askama_axum::IntoResponse; -use templates::{hello::HelloResponse, index::GetIndexResponse}; +use axum::http::{StatusCode, Uri}; use tower_http::services::ServeDir; -async fn root() -> impl IntoResponse { - return GetIndexResponse {}.into_response(); +async fn fallback(uri: Uri) -> (StatusCode, String) { + (StatusCode::NOT_FOUND, format!("No route for {uri}")) } -async fn hello() -> impl IntoResponse { - return HelloResponse { - name: "Theo".to_string(), - } - .into_response(); +#[derive(Template)] +#[template(path = "index.html")] +pub struct GetIndexResponse; + +async fn root() -> impl IntoResponse { + GetIndexResponse {}.into_response() } pub fn get_router(assets_path: &Path) -> axum::Router { - let router = axum::Router::new() + axum::Router::new() .nest_service("/assets", ServeDir::new(assets_path)) .route("/", axum::routing::get(root)) - .route("/hello", axum::routing::get(hello)); - - router + .merge(templates::get_routes()) + .fallback(fallback) } diff --git a/crates/app/src/templates/hello.rs b/crates/app/src/templates/hello.rs index 9ec4fb3..20321a4 100644 --- a/crates/app/src/templates/hello.rs +++ b/crates/app/src/templates/hello.rs @@ -1,7 +1,20 @@ use askama::Template; +use askama_axum::IntoResponse; +use axum::{routing, Router}; #[derive(Template)] #[template(path = "hello.html")] -pub struct HelloResponse { +struct HelloResponse { pub name: String, } + +async fn hello() -> impl IntoResponse { + HelloResponse { + name: "Theo".to_string(), + }.into_response() +} + +pub fn get_routes() -> Router { + Router::new() + .route("/", routing::get(hello)) +} diff --git a/crates/app/src/templates/index.rs b/crates/app/src/templates/index.rs deleted file mode 100644 index 49e09e7..0000000 --- a/crates/app/src/templates/index.rs +++ /dev/null @@ -1,5 +0,0 @@ -use askama::Template; - -#[derive(Template)] -#[template(path = "index.html")] -pub struct GetIndexResponse; diff --git a/crates/app/src/templates/mod.rs b/crates/app/src/templates/mod.rs index bb7cbb8..11b9607 100644 --- a/crates/app/src/templates/mod.rs +++ b/crates/app/src/templates/mod.rs @@ -1,2 +1,8 @@ -pub mod hello; -pub mod index; +use axum::Router; + +mod hello; + +pub fn get_routes() -> Router { + Router::new() + .nest("/hello", hello::get_routes()) +}