Files
fleen/src/server.rs
T

59 lines
1.9 KiB
Rust
Raw Normal View History

2025-09-01 19:15:30 -05:00
use std::fs;
2025-09-01 17:32:45 -05:00
use std::path::PathBuf;
use std::sync::Arc;
2025-09-01 19:15:30 -05:00
use axum::body::Body;
2025-09-01 17:32:45 -05:00
use axum::extract::State;
2025-09-01 19:15:30 -05:00
use axum::http::Uri;
2025-09-01 17:32:45 -05:00
use axum::response::{IntoResponse, Response};
use axum::Router;
use axum::routing::get;
use crate::renderer::{default_path, render, RenderOutput};
pub async fn start_server(root: PathBuf) {
let state = Arc::new(root);
let app = Router::new()
2025-09-01 19:15:30 -05:00
.route("/", get(|State(root): State<Arc<PathBuf>>| async {
let path = default_path(&root);
serve_path(String::from(path.to_str().unwrap()), root)
}))
.route("/{*path}", get(|State(root): State<Arc<PathBuf>>, uri: Uri| async move {
serve_path(String::from(uri.path()), root)
}))
2025-09-01 17:32:45 -05:00
.with_state(state);
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
fn serve_path(path: String, root: impl AsRef<PathBuf>) -> impl IntoResponse {
2025-09-01 19:15:30 -05:00
let path = path.strip_prefix("/").unwrap_or(path.as_str());
2025-09-01 17:32:45 -05:00
let render = render(path.into(), root.as_ref());
2025-09-01 19:15:30 -05:00
2025-09-01 17:32:45 -05:00
match render {
2025-09-01 19:15:30 -05:00
Ok(RenderOutput::Rendered(_, content)) |
Ok(RenderOutput::Hidden(_, content)) => {
Response::builder()
.status(200)
.body(Body::from(content)).unwrap()
}
Ok(RenderOutput::RawFile(file)) => {
2025-09-01 17:32:45 -05:00
Response::builder()
.status(200)
2025-09-01 19:15:30 -05:00
.body(Body::from(fs::read(file).unwrap_or(vec![]))).unwrap()
2025-09-01 17:32:45 -05:00
}
Ok(RenderOutput::NoOutput) |
Ok(RenderOutput::Dir(_)) => {
Response::builder()
.status(404)
2025-09-01 19:15:30 -05:00
.body(Body::from(include_str!("../templates/404.html"))).unwrap()
2025-09-01 17:32:45 -05:00
}
Err(err) => {
Response::builder()
.status(500)
2025-09-01 19:15:30 -05:00
.body(Body::from(format!("{}", err))).unwrap()
2025-09-01 17:32:45 -05:00
}
}
}