From 1313ba8a5845cc361495fbc8b197f35336e02a16 Mon Sep 17 00:00:00 2001 From: 53hornet Date: Sat, 28 Aug 2021 22:18:45 -0400 Subject: feat(evals): moved from PHP to Rust+Warp --- src/main.rs | 56 +++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index cbabc10..5359661 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,7 @@ use handlebars::Handlebars; use serde::Serialize; -use serde_json::json; use std::sync::Arc; -use std::time::SystemTime; -use warp::{Filter, Rejection}; +use warp::{http::Uri, Filter, Rejection}; #[tokio::main] async fn main() -> Result<(), Box> { @@ -11,10 +9,14 @@ async fn main() -> Result<(), Box> { let mut hbs = Handlebars::new(); hbs.register_template_file("base", "templates/base.hbs")?; hbs.register_template_file("index", "templates/index.hbs")?; + hbs.register_template_file("policies", "templates/policies.hbs")?; + hbs.register_template_file("about", "templates/about.hbs")?; let hbs = Arc::new(hbs); // Build routes let routes = index_filter(hbs.clone()) + .or(template_filter(hbs.clone())) + .or(redirect_static_ext()) .or(evals_list()) .or(warp::fs::dir("static")); @@ -30,7 +32,44 @@ fn index_filter( ) -> impl Filter + Clone { warp::get() .and(warp::path::end()) - .map(move || render("index", hbs.clone(), json!({"year", year().unwrap()}))) + .map(move || render("index", hbs.clone(), "")) +} + +fn template_filter( + hbs: Arc>, +) -> impl Filter + Clone { + warp::path!(String).and_then(move |name: String| { + let hbs = hbs.clone(); + async move { + if hbs.has_template(&name) { + Ok(render(&name, hbs, "")) + } else { + Err(warp::reject::not_found()) + } + } + }) +} + +fn redirect_static_ext() -> impl Filter + Clone { + warp::path!(String).and_then(move |path: String| async move { + if let Some(prefix) = path.strip_suffix(".php") { + return Ok(warp::redirect( + prefix + .parse::() + .unwrap_or_else(|_| Uri::from_static("/")), + )); + } + + if let Some(prefix) = path.strip_suffix(".html") { + return Ok(warp::redirect( + prefix + .parse::() + .unwrap_or_else(|_| Uri::from_static("/")), + )); + } + + Err(warp::reject::not_found()) + }) } fn evals_list() -> impl Filter + Clone { @@ -49,12 +88,3 @@ where .unwrap_or_else(|err| err.to_string()); warp::reply::html(render) } - -const UNIX_YEAR: u64 = 31556926; - -fn year() -> Result> { - let date = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH)? - .as_secs(); - Ok(date / UNIX_YEAR) -} -- cgit v1.2.3