65 lines
2 KiB
Rust
65 lines
2 KiB
Rust
use actix_files::Files;
|
|
use actix_web::{
|
|
dev::{fn_service, ServiceRequest, ServiceResponse},
|
|
get, middleware, App, HttpResponse, HttpServer, Responder,
|
|
};
|
|
|
|
use std::path::PathBuf;
|
|
|
|
pub async fn run(bind_addr: &str, root: &PathBuf) -> std::io::Result<()> {
|
|
let root_ = root.clone();
|
|
let s = HttpServer::new(move || {
|
|
let static_files = Files::new("/", &root_)
|
|
.prefer_utf8(true)
|
|
.index_file("index.html")
|
|
.use_hidden_files()
|
|
.show_files_listing()
|
|
.redirect_to_slash_directory()
|
|
.files_listing_renderer(crate::directory_listing::directory_listing)
|
|
.default_handler(fn_service(|req: ServiceRequest| async {
|
|
let (req, _) = req.into_parts();
|
|
let style = include_str!("style.css");
|
|
|
|
let html = format!(
|
|
"<!DOCTYPE html>\n\
|
|
<html>\n\
|
|
<head>\n\
|
|
<title>Error</title>\n\
|
|
<style>\n{}</style></head>\n\
|
|
<body>\n\
|
|
<h1>Error</h1>\
|
|
<p>File not found</p>\
|
|
</body>\n</html>",
|
|
style
|
|
);
|
|
|
|
Ok(ServiceResponse::new(
|
|
req,
|
|
HttpResponse::NotFound()
|
|
.content_type("text/html; charset=utf-8")
|
|
.body(html),
|
|
))
|
|
}));
|
|
|
|
App::new()
|
|
.app_data(root_.clone())
|
|
.wrap(middleware::Logger::default())
|
|
.service(favicon_ico)
|
|
.service(static_files)
|
|
})
|
|
.bind(bind_addr)?
|
|
.run();
|
|
|
|
log::info!("Serving files from {:?}", &root);
|
|
s.await
|
|
}
|
|
|
|
const FAVICON_ICO: &[u8] = include_bytes!("favicon.png");
|
|
|
|
#[get("/favicon.ico")]
|
|
async fn favicon_ico() -> impl Responder {
|
|
HttpResponse::Ok()
|
|
.content_type("image/png")
|
|
.append_header(("Cache-Control", "only-if-cached, max-age=86400"))
|
|
.body(FAVICON_ICO)
|
|
}
|