From 1fd606031d018854d2b8d08d30863105567fcccc Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Fri, 4 Aug 2023 17:00:11 +0100 Subject: Add pretty urls This adds a new flag namely `--pretty-urls` that when enabled will serve the equivalent `.html` if it exists. Very much the same approach that [`netlify` uses](https://docs.netlify.com/site-deploys/post-processing/). It can be quite useful when having hrefs like `/about` serve `/about.html`. --- src/main.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 851f9ab..43878db 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,9 @@ use std::time::Duration; use actix_files::NamedFile; use actix_web::{ - http::header::ContentType, middleware, web, App, HttpRequest, HttpResponse, Responder, + dev::{fn_service, ServiceRequest, ServiceResponse}, + http::header::ContentType, + middleware, web, App, HttpRequest, HttpResponse, Responder, }; use actix_web_httpauth::middleware::HttpAuthentication; use anyhow::Result; @@ -316,6 +318,26 @@ fn configure_app(app: &mut web::ServiceConfig, conf: &MiniserveConfig) { } } + if conf.pretty_urls { + log::info!("Pretty URLs enabled."); + files = files.default_handler(fn_service(|req: ServiceRequest| async { + let (req, _) = req.into_parts(); + let conf = req + .app_data::() + .expect("Could not get miniserve config"); + let mut path_base = req.path()[1..].to_string(); + if path_base.ends_with('/') { + path_base.pop(); + } + if !path_base.ends_with("html") { + path_base = format!("{}.html", path_base); + } + let file = NamedFile::open_async(conf.path.join(path_base)).await?; + let res = file.into_response(&req); + Ok(ServiceResponse::new(req, res)) + })); + } + if conf.show_hidden { files = files.use_hidden_files(); } -- cgit v1.2.3