1
0
Fork 0
website/src/main.rs

85 lines
2.2 KiB
Rust
Raw Normal View History

2022-08-31 23:20:59 +02:00
use std::{path::PathBuf, sync::Arc};
2022-09-05 00:02:58 +02:00
use axum::{routing::{get, get_service}, Extension, Router, handler::Handler, http::StatusCode};
2022-08-31 23:25:17 +02:00
use color_eyre::eyre::Result;
2022-08-31 23:20:59 +02:00
use glob::glob;
use serde_derive::Serialize;
use tera::Tera;
2022-06-16 23:44:37 +02:00
use tower_http::trace::TraceLayer;
2022-08-31 23:20:59 +02:00
use tracing::log::*;
2022-06-16 23:44:37 +02:00
2022-08-31 23:20:59 +02:00
mod handlers;
pub struct State {
posts: Vec<Post>,
tera: Tera,
}
#[derive(Serialize)]
pub struct Post {
2022-09-05 00:02:58 +02:00
pub slug: String,
2022-08-31 23:20:59 +02:00
pub content: String,
}
2022-06-16 23:44:37 +02:00
#[tokio::main]
async fn main() -> Result<()> {
color_eyre::install()?;
tracing_subscriber::fmt::init();
info!("Starting server...");
2022-08-31 23:20:59 +02:00
let tera = Tera::new("templates/**/*")?;
2022-08-31 23:25:17 +02:00
let posts = glob("posts/**/*.md")?
.map(|p| {
let path = p.unwrap();
2022-09-05 00:02:58 +02:00
let filename = path
2022-08-31 23:25:17 +02:00
.file_name()
.unwrap()
2022-09-05 00:02:58 +02:00
.to_string_lossy();
let (filename, _) = filename.rsplit_once('.')
.unwrap();
let slug = if filename.eq_ignore_ascii_case("index") {
path.parent().unwrap().file_name().unwrap().to_string_lossy().into_owned()
}
else {
filename.to_owned()
};
2022-08-31 23:25:17 +02:00
Post {
2022-09-05 00:02:58 +02:00
slug,
2022-08-31 23:25:17 +02:00
content: std::fs::read_to_string(&path).unwrap(),
}
})
.collect();
2022-06-16 23:44:37 +02:00
2022-08-31 23:20:59 +02:00
let state = Arc::new(State { tera, posts });
2022-06-16 23:44:37 +02:00
2022-08-31 23:20:59 +02:00
let middleware = tower::ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(Extension(state.clone()));
2022-08-31 23:25:17 +02:00
let app = Router::new()
2022-08-31 23:20:59 +02:00
.route("/", get(handlers::index))
2022-09-05 00:02:58 +02:00
.route("/posts/", get(handlers::posts::index))
.route("/posts/:slug/", get(handlers::posts::view))
.nest("/static", get_service(tower_http::services::ServeDir::new("./static")).handle_error(|e| async {
(StatusCode::NOT_FOUND, "not found")
}))
.fallback((|| async { (StatusCode::NOT_FOUND, "not found") }).into_service())
2022-08-31 23:25:17 +02:00
.layer(middleware);
2022-06-16 23:44:37 +02:00
info!("Now listening at http://localhost:8180");
axum::Server::bind(&"0.0.0.0:8180".parse().unwrap())
.serve(app.into_make_service())
.await?;
Ok(())
}
2022-09-05 00:02:58 +02:00
async fn healthcheck() -> &'static str {
"OK"
}