How to serve static files from a compiled binary? #2005
Replies: 2 comments 9 replies
-
@tobymurray If you still need to serve whole directory cause i.e. you have some auth which can't be handeled by a reverse proxy then fair. Use rust, safe and sound. Now about handling and including a whole directory in a binary. Your binary needs to be loaded into memory, this means if you got multiple megabytes of css, js, html, wasm or any assets included these would need to be loaded in memory as you start your rocket server. If you would use the traditional way just like nginx, apache and others and put the files into a directory only the ones needed would be loaded into memory. Now I have no clue how much you wanna serve, general rule, if it means your binary will result over 32mb, don't do it, just use the Now for the sake of leaving an answer on how to do what you mean. Here we go.... https://docs.rs/include_dir/latest/include_dir/ just include a whole directory in your binary and create a wrapper just like Now you asked how others do it, me, I'm using nginx, cause it does what it needs to do efficiently and silent. Now if your 3rd question means that you would like to specify the "static/" folder on server startup. It's just a 🍺 Cheers |
Beta Was this translation helpful? Give feedback.
-
static PROJECT_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../web");
#[rocket::get("/<path..>", rank = 100)]
async fn static_files(path: PathBuf) -> (Status, (ContentType, &'static str)) {
let ext = if let Some(path) = path.extension() {
path.to_str().unwrap()
} else {
""
};
let content_type = match ext {
"css" => ContentType::CSS,
"htm" => ContentType::HTML,
"html" => ContentType::HTML,
"jpg" => ContentType::JPEG,
"jpeg" => ContentType::JPEG,
"png" => ContentType::PNG,
"gif" => ContentType::GIF,
"js" => ContentType::JavaScript,
"json" => ContentType::JSON,
"txt" => ContentType::Plain,
"ico" => ContentType::Icon,
"" => ContentType::Plain,
_ => ContentType::Binary,
};
if let Some(file) = PROJECT_DIR.get_file(path) {
let content = file.contents_utf8().unwrap_or("");
return (Status::Ok, (content_type, content));
}
(Status::NotFound, (content_type, "Fild not found"))
} Here is how I do it in rocket v.0.5.0. Register a handler with lowest priority |
Beta Was this translation helpful? Give feedback.
-
The guide contains:
This looks like it would be serving a relative path. Looking at the docs, it seems like the
path
examples are always absolute and to get a relative path the relative! macro should be used.Naively compiling my Rocket application, my understanding is this will bake in
CARGO_MANIFEST_DIR
(the path to the crate on the machine building the binary). Obviously this doesn't work for running the machine on a separate host.How are people serving static files? Are they building them into their binary? Is there an idiomatic way to provide a path at runtime?
Beta Was this translation helpful? Give feedback.
All reactions