static_files: embed files in-binary

Signed-off-by: Gunwant Jain <mail@wantguns.dev>
This commit is contained in:
Gunwant Jain
2022-01-18 12:16:07 +05:30
parent e91393f63c
commit 892e84348d
3 changed files with 115 additions and 12 deletions

View File

@@ -1,10 +1,21 @@
use rocket::fs::NamedFile;
use rocket::response::status::NotFound;
use std::path::{Path, PathBuf};
use rocket::http::ContentType;
use rust_embed::RustEmbed;
use std::{borrow::Cow, ffi::OsStr, path::PathBuf};
#[derive(RustEmbed)]
#[folder = "static/"]
struct Static;
#[get("/static/<file..>")]
pub async fn static_files(file: PathBuf) -> Result<NamedFile, NotFound<String>> {
NamedFile::open(Path::new("static/").join(file))
.await
.map_err(|e| NotFound(e.to_string()))
pub fn static_files(file: PathBuf) -> Option<(ContentType, Cow<'static, [u8]>)> {
let filename = file.display().to_string();
let asset = Static::get(&filename)?;
let content_type = file
.extension()
.and_then(OsStr::to_str)
.and_then(ContentType::from_extension)
.unwrap_or(ContentType::Bytes);
Some((content_type, asset.data))
}