This commit is contained in:
insects 2025-02-03 17:57:43 +01:00
commit 5dc1b3d1ff
7 changed files with 980 additions and 0 deletions

68
src/main.rs Normal file
View file

@ -0,0 +1,68 @@
use std::{env, path::PathBuf, sync::Arc};
use axum::{
extract::State,
http::StatusCode,
response::{Html, IntoResponse},
routing::get,
Router,
};
use minijinja::{context, path_loader, Environment};
use minijinja_autoreload::AutoReloader;
pub struct AppState {
pub templates: AutoReloader,
}
pub struct AppError(anyhow::Error);
impl IntoResponse for AppError {
fn into_response(self) -> axum::response::Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}
#[axum::debug_handler]
async fn main_handler(state: State<Arc<AppState>>) -> Result<Html<String>, AppError> {
let templates = state.templates.acquire_env()?;
let template = templates.get_template("index.html")?;
let html = template.render(context! {})?;
Ok(Html(html))
}
#[tokio::main]
async fn main() {
let disable_autoreload = env::var("DISABLE_AUTORELOAD").as_deref() == Ok("1");
let reloader = AutoReloader::new(move |notifier| {
let template_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("templates");
let mut tmp = Environment::new();
tmp.set_loader(path_loader(&template_path));
notifier.set_fast_reload(true);
if !disable_autoreload {
notifier.watch_path(&template_path, true);
}
Ok(tmp)
});
let app = Router::new()
.route("/", get(main_handler))
.with_state(Arc::new(AppState {
templates: reloader,
}));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000!");
axum::serve(listener, app).await.unwrap();
}