initial
This commit is contained in:
commit
5dc1b3d1ff
7 changed files with 980 additions and 0 deletions
68
src/main.rs
Normal file
68
src/main.rs
Normal 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();
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue