Skip to content

Instantly share code, notes, and snippets.

@bitexploder
Created December 1, 2022 23:26
Show Gist options
  • Save bitexploder/499fd51ad5663be6035d392de2f9071d to your computer and use it in GitHub Desktop.
Save bitexploder/499fd51ad5663be6035d392de2f9071d to your computer and use it in GitHub Desktop.
use include_dir::{include_dir, Dir};
static STATIC_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/assets/webroot");
fn ct_from_path(path: &str) -> &'static str {
let idx = path.rfind(".").unwrap_or_else(|| 0);
let suffix = path.get(idx..).unwrap_or_else(|| ".unknown");
match suffix {
".css" => "text/css",
".html" => "text/html",
_ => "text/plain",
}
}
pub async fn file_handler(uri: Uri) -> impl IntoResponse {
let uri_path = uri.path();
// STATIC_DIR paths don't have a leading `/`
let mut internal_path = uri_path.get(1..).unwrap_or_else(|| "static/index.html");
// Special magic if path is `/`
if internal_path.len() == 0 {
internal_path = "static/index.html";
}
let content_bytes = STATIC_DIR.get_file(internal_path);
let ct = ct_from_path(internal_path);
if content_bytes.is_some() {
(
StatusCode::OK,
[(header::CONTENT_TYPE, ct)],
content_bytes.unwrap().contents_utf8().unwrap(),
)
} else {
(
StatusCode::NOT_FOUND,
[(header::CONTENT_TYPE, "text/html")],
"<html><body>Not found</body></html>",
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment