From 6be5525bae122a1afc410d025b3012dfc10e5ad2 Mon Sep 17 00:00:00 2001 From: Adrian Hedqvist Date: Wed, 29 Mar 2023 18:19:39 +0200 Subject: [PATCH] implement post aliases --- src/handlers/mod.rs | 3 ++- src/handlers/posts.rs | 17 ++++++++++++++++- src/main.rs | 3 ++- templates/index.html | 2 +- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index e4fe2b2..97d1238 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -20,10 +20,11 @@ lazy_static! { .unwrap(); } -pub fn routes() -> Router> { +pub fn routes(state: &Arc) -> Router> { Router::new() .route("/", get(index)) .nest("/posts", posts::router()) + .merge(posts::alias_router(state.posts.values())) .route("/healthcheck", get(healthcheck)) .route("/metrics", get(metrics)) .nest_service("/static", tower_http::services::ServeDir::new("./static")) diff --git a/src/handlers/posts.rs b/src/handlers/posts.rs index c49c8bf..f5652b0 100644 --- a/src/handlers/posts.rs +++ b/src/handlers/posts.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use axum::{extract::{Path, State}, response::Html, routing::get, Extension, Router}; +use axum::{extract::{Path, State}, response::{Html, Redirect}, routing::get, Extension, Router}; use serde_derive::Serialize; use tracing::{instrument, log::*}; @@ -17,6 +17,21 @@ pub fn router() -> Router> { .fallback_service(tower_http::services::ServeDir::new("./posts")) } +pub fn alias_router<'a>(posts: impl IntoIterator) -> Router> { + let mut router = Router::new(); + + for post in posts { + for alias in &post.aliases { + let path = post.absolute_path.to_owned(); + router = router.route(alias, get(move || async { + let path = path; + Redirect::permanent(&path) + })); + } + } + router +} + #[derive(Serialize, Debug)] struct PageContext<'a> { title: &'a str, diff --git a/src/main.rs b/src/main.rs index e7fbbef..0123040 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,7 +27,8 @@ async fn main() -> Result<()> { let posts = post::load_all().await?; let state = Arc::new(AppState { tera, posts }); - let app = handlers::routes() + + let app = handlers::routes(&state) .layer(TraceLayer::new_for_http()) .layer(CompressionLayer::new()) .with_state(state); diff --git a/templates/index.html b/templates/index.html index d6b3d4c..127a21d 100644 --- a/templates/index.html +++ b/templates/index.html @@ -11,7 +11,7 @@
  • ✅ post metadata (frontmatter, toml)
  • ✅ app metrics (page hits, etc)
  • ✅ tests
  • -
  • ⬜ page aliases (redirects, for back-compat with old routes)
  • +
  • ✅ page aliases (redirects, for back-compat with old routes)
  • ⬜ sass compilation (using rsass? grass?)
  • ⬜ rss/atom/jsonfeed
  • ✅ proper error handling (i guess??)