1
0
Fork 0
website/src/main.rs

88 lines
2.2 KiB
Rust
Raw Normal View History

2022-09-05 00:05:24 +02:00
use std::sync::Arc;
use axum::{
handler::Handler,
http::StatusCode,
routing::{get, get_service},
Extension, Router,
};
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
2022-09-05 00:05:24 +02:00
let filename = path.file_name().unwrap().to_string_lossy();
2022-09-05 00:02:58 +02:00
2022-09-05 00:05:24 +02:00
let (filename, _) = filename.rsplit_once('.').unwrap();
2022-09-05 00:02:58 +02:00
let slug = if filename.eq_ignore_ascii_case("index") {
2022-09-05 00:05:24 +02:00
path.parent()
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
} else {
2022-09-05 00:02:58 +02:00
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))
2022-09-05 00:05:24 +02:00
.nest(
"/static",
get_service(tower_http::services::ServeDir::new("./static"))
.handle_error(|_e| async { (StatusCode::NOT_FOUND, "not found") }),
)
2022-09-05 00:02:58 +02:00
.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(())
}