1
0
Fork 0
website/src/main.rs

85 lines
2.1 KiB
Rust
Raw Normal View History

2022-09-05 00:05:24 +02:00
use std::sync::Arc;
use axum::{
2023-03-22 23:55:30 +01:00
routing::get,
Extension, Router,
2022-09-05 00:05:24 +02:00
};
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 {
2023-03-22 22:39:18 +01:00
pub name: String,
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();
2023-03-22 22:39:18 +01:00
info!("found page: {}", path.display());
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 {
2023-03-22 22:39:18 +01:00
name: slug.clone(),
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))
2023-03-22 23:52:57 +01:00
.nest("/posts", Router::new()
.route("/", get(handlers::posts::index))
.route("/:route/", get(handlers::posts::view))
.fallback_service(tower_http::services::ServeDir::new("./posts")))
2023-03-22 22:39:18 +01:00
.nest_service("/static", tower_http::services::ServeDir::new("./static"))
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(())
}