summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
author53hornet <atc@53hor.net>2021-08-22 11:03:36 -0400
committer53hornet <atc@53hor.net>2021-08-22 11:03:36 -0400
commit7494b946920bf93fa12ac1fc71a07b1165a203e2 (patch)
tree0003ebcdb595c53a0a8bb1cde8cf54b94a52c3f7 /src
parentf2e39406302c3b79a608a6f20e058a084401c6eb (diff)
downloadcarpentertutoring-7494b946920bf93fa12ac1fc71a07b1165a203e2.tar.xz
carpentertutoring-7494b946920bf93fa12ac1fc71a07b1165a203e2.zip
begin migrate to warp for evals functionality and site server
Diffstat (limited to 'src')
-rw-r--r--src/main.rs60
1 files changed, 60 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..cbabc10
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,60 @@
+use handlebars::Handlebars;
+use serde::Serialize;
+use serde_json::json;
+use std::sync::Arc;
+use std::time::SystemTime;
+use warp::{Filter, Rejection};
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Build template registry
+ let mut hbs = Handlebars::new();
+ hbs.register_template_file("base", "templates/base.hbs")?;
+ hbs.register_template_file("index", "templates/index.hbs")?;
+ let hbs = Arc::new(hbs);
+
+ // Build routes
+ let routes = index_filter(hbs.clone())
+ .or(evals_list())
+ .or(warp::fs::dir("static"));
+
+ // Start server
+ warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
+
+ // Done
+ Ok(())
+}
+
+fn index_filter(
+ hbs: Arc<Handlebars<'static>>,
+) -> impl Filter<Extract = (impl warp::Reply,), Error = Rejection> + Clone {
+ warp::get()
+ .and(warp::path::end())
+ .map(move || render("index", hbs.clone(), json!({"year", year().unwrap()})))
+}
+
+fn evals_list() -> impl Filter<Extract = (&'static str,), Error = Rejection> + Clone {
+ warp::get()
+ .and(warp::path("evals"))
+ .and(warp::path::end())
+ .map(|| "evals here")
+}
+
+fn render<T>(template: &str, hbs: Arc<Handlebars>, value: T) -> impl warp::Reply
+where
+ T: Serialize,
+{
+ let render = hbs
+ .render(template, &value)
+ .unwrap_or_else(|err| err.to_string());
+ warp::reply::html(render)
+}
+
+const UNIX_YEAR: u64 = 31556926;
+
+fn year() -> Result<u64, Box<dyn std::error::Error>> {
+ let date = SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)?
+ .as_secs();
+ Ok(date / UNIX_YEAR)
+}