Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev.
You can use this to embed your css, js and images into a single executable which can be deployed to your servers. Also it makes it easy to build a very small docker image for you to deploy.
toml
[dependencies]
rust-embed="5.2.0"
You need to add the custom derive macro RustEmbed to your struct with an attribute folder
which is the path to your static folder.
The path resolution works as follows:
debug
and when debug-embed
feature is not enabled, the folder path is resolved relative to where the binary is run from.release
or when debug-embed
feature is enabled, the folder path is resolved relative to where Cargo.toml
is.```rust
struct Asset; ```
The macro will generate the following code:
```rust
impl Asset {
pub fn get(file_path: &str) -> Option pub fn iter() -> impl Iterator Given a relative path from the assets folder returns the bytes if found. If the feature Otherwise the bytes are read from the file system on each call and a Iterates the files in this assets folder. If the feature Otherwise the files are listed from the file system on each call. Always embed the files in the binary, even in debug mode. Allow environment variables to be used in the ```rust struct Asset;
``` This will pull the Compress each file when embedding into the binary. Compression is done via [ ```rust extern crate rust_embed; struct Asset; fn main() {
let indexhtml = Asset::get("index.html").unwrap();
println!("{:?}", std::str::fromutf8(indexhtml.asref())); for file in Asset::iter() {
println!("{}", file.as_ref());
}
}
``` To run the example in dev mode where it reads from the fs, To run the example in release mode where it reads from binary, Note: To run the Note: To run the debug: release: Go Rusketeers!
The power is yours!get(file_path: &str)
debug-embed
is enabled or the binary compiled in release mode the bytes have been embeded in the binary and a Cow::Borrowed(&'static [u8])
is returned.Cow::Owned(Vec<u8>)
is returned.iter()
debug-embed
is enabled or the binary compiled in release mode a static array to the list of relative paths to the files is returned.Features
debug-embed
interpolate-folder-path
folder
path. Example:[derive(RustEmbed)]
[folder = "$CARGOMANIFESTDIR/foo"]
foo
directory relative to your Cargo.toml
file.compression
include-flate
].Usage
[macro_use]
[derive(RustEmbed)]
[folder = "examples/public/"]
Examples
cargo run --example basic
cargo run --example basic --release
actix-web
example:cargo run --example actix --features actix
rocket
example, add the nightly
feature flag and run on a nightly build:cargo +nightly run --example rocket --features nightly
Testing
cargo test --test lib
cargo test --test lib --release