### Build Basic Example Source: https://pyrossh.dev/repos/rust-embed Compiles the 'basic' example. ```bash cargo build --example basic ``` -------------------------------- ### Build Basic Example in Release Source: https://pyrossh.dev/repos/rust-embed Compiles the 'basic' example in release mode. ```bash cargo build --example basic --release ``` -------------------------------- ### Basic Usage Example Source: https://pyrossh.dev/repos/rust-embed/files/README.md Demonstrates how to use the `get` method to retrieve a file and `iter` to list all embedded files. Assumes a prefix is set. ```rust use rust_embed::Embed; #[derive(Embed)] #[folder = "examples/public/"] #[prefix = "prefix/"] struct Asset; fn main() { let index_html = Asset::get("prefix/index.html").unwrap(); println!("{:?}", std::str::from_utf8(index_html.data.as_ref())); for file in Asset::iter() { println!("{}", file.as_ref()); } } ``` -------------------------------- ### Basic Usage Example Source: https://pyrossh.dev/repos/rust-embed Demonstrates how to get a specific file and iterate over all embedded files using the generated methods. ```rust use rust_embed::Embed; #[derive(Embed)] #[folder = "examples/public/"] #[prefix = "prefix/"] struct Asset; fn main() { let index_html = Asset::get("prefix/index.html").unwrap(); println!("{:?}", std::str::from_utf8(index_html.data.as_ref())); for file in Asset::iter() { println!("{}", file.as_ref()); } } ``` -------------------------------- ### Example Commands Source: https://pyrossh.dev/repos/rust-embed/commits/48814079dd4a066cf15598964002d31649222c6e Provides example cargo commands for running and building examples with different features and configurations. ```sh cargo run --example basic # dev mode where it reads from the fs cargo run --example basic --release # release mode where it reads from binary cargo run --example actix --features actix # https://github.com/actix/actix-web cargo run --example rocket --features rocket # https://github.com/SergioBenitez/Rocket cargo run --example warp --features warp-ex # https://github.com/seanmonstar/warp cargo run --example axum --features axum-ex # https://github.com/tokio-rs/axum cargo run --example poem --features poem-ex # https://github.com/poem-web/poem cargo run --example salvo --features salvo-ex # https://github.com/salvo-rs/salvo ``` -------------------------------- ### Build Axum Example with Feature Source: https://pyrossh.dev/repos/rust-embed Compiles the 'axum' example, enabling the 'axum-ex' feature. ```bash cargo build --example axum --features axum-ex ``` -------------------------------- ### Running Basic Example in Release Mode Source: https://pyrossh.dev/repos/rust-embed/commits/41b5a2ddb440867fb3904944c83a11acb0137562 To run the basic example in release mode, where files are read from the embedded binary, use the 'cargo run --release' command with the example name. ```bash cargo run --release --example basic ``` -------------------------------- ### Building Examples for Different Configurations Source: https://pyrossh.dev/repos/rust-embed/files/README.md These commands build the rust-embed examples. They cover building specific examples like 'basic' and web framework integrations, with and without the release flag. ```sh cargo build --example basic cargo build --example rocket --features rocket cargo build --example actix --features actix cargo build --example axum --features axum-ex cargo build --example warp --features warp-ex cargo build --example basic --release cargo build --example rocket --features rocket --release cargo build --example actix --features actix --release cargo build --example axum --features axum-ex --release cargo build --example warp --features warp-ex --release ``` -------------------------------- ### Build Actix Example with Feature Source: https://pyrossh.dev/repos/rust-embed Compiles the 'actix' example, enabling the 'actix' feature. ```bash cargo build --example actix --features actix ``` -------------------------------- ### Run Rocket Example Source: https://pyrossh.dev/repos/rust-embed/commits/b8c122cdbb4954ee6f346ad55ecfa6bd12705304 To run the 'rocket' example, which integrates with the Rocket framework, enable the 'rocket' feature. ```sh cargo run --example rocket --features rocket ``` -------------------------------- ### Poem Web Server with Rust-Embed Source: https://pyrossh.dev/repos/rust-embed/commits/524927fb4144080d216a926345edf3b31ba52f85 This example demonstrates using rust-embed with the Poem web framework to serve static files. It includes handling GET requests, setting ETag headers, and serving files from the 'examples/public/' directory. ```rust use poem::{ async_trait, http::{header, Method, StatusCode}, listener::TcpListener, Endpoint, Request, Response, Route, Server, }; #[tokio::main] async fn main() -> Result<(), std::io::Error> { let app = Route::new().at("/", StaticEmbed).at("/index.html", StaticEmbed).nest("/dist", StaticEmbed); let listener = TcpListener::bind("127.0.0.1:3000"); let server = Server::new(listener).await?; server.run(app).await?; Ok(()) } #[derive(rust_embed::RustEmbed)] #[folder = "examples/public/"] struct Asset; pub(crate) struct StaticEmbed; #[async_trait] impl Endpoint for StaticEmbed { type Output = Response; async fn call(&self, req: Request) -> Self::Output { if req.method() != Method::GET { return StatusCode::METHOD_NOT_ALLOWED.into(); } let mut path = req.uri().path().trim_start_matches('/').trim_end_matches('/').to_string(); if path.starts_with("dist/") { path = path.replace("dist/", ""); } else if path.is_empty() { path = "index.html".to_string(); } let path = path.as_ref(); match Asset::get(path) { Some(content) => { let hash = hex::encode(content.metadata.sha256_hash()); // if etag is matched, return 304 if req .headers() .get(header::IF_NONE_MATCH) .map(|etag| etag.to_str().unwrap_or("000000").eq(&hash)) .unwrap_or(false) { return StatusCode::NOT_MODIFIED.into(); } // otherwise, return 200 with etag hash let body: Vec = content.data.into(); let mime = mime_guess::from_path(path).first_or_octet_stream(); Response::builder() .header(header::CONTENT_TYPE, mime.as_ref()) .header(header::ETAG, hash) .body(body) } None => Response::builder().status(StatusCode::NOT_FOUND).finish(), } } } ``` -------------------------------- ### Release Command Example Source: https://pyrossh.dev/repos/rust-embed/commits/647cc1b44fd257d64f158db101061b7c5d32bfbb Example of a release command for testing the library. ```bash release: `cargo test --test lib --release` ``` -------------------------------- ### Run Example in Development Mode Source: https://pyrossh.dev/repos/rust-embed/commits/582feabacc181ea9febe957c30b21b275fd9eab6 To run the example in dev mode where it reads from the file system, use this cargo command. ```bash cargo run --example rocket ``` -------------------------------- ### Run HTTP Example Source: https://pyrossh.dev/repos/rust-embed/commits/26bf2b616733691738b6380ce97500cf5ffd607f Compile and run the HTTP server example that serves embedded resources. ```bash cargo run --example http ``` -------------------------------- ### Run Actix Example Source: https://pyrossh.dev/repos/rust-embed/commits/9761757df0668e9ef4e6e7a73131b6b3f39ee2e6 Run the actix-web example. Requires the 'actix' feature flag to be enabled. ```bash cargo run --example actix --features actix ``` -------------------------------- ### Run Basic Example in Release Mode Source: https://pyrossh.dev/repos/rust-embed/commits/b8c122cdbb4954ee6f346ad55ecfa6bd12705304 Use this command to run the 'basic' example in release mode, where files are embedded into the binary and read from there. ```sh cargo run --example basic --release ``` -------------------------------- ### Build Axum Example with Feature in Release Source: https://pyrossh.dev/repos/rust-embed Compiles the 'axum' example, enabling the 'axum-ex' feature, in release mode. ```bash cargo build --example axum --features axum-ex --release ``` -------------------------------- ### Build Warp Example with Feature Source: https://pyrossh.dev/repos/rust-embed Compiles the 'warp' example, enabling the 'warp-ex' feature. ```bash cargo build --example warp --features warp-ex ``` -------------------------------- ### Embed Folder Example Source: https://pyrossh.dev/repos/rust-embed/commits/a398d8807fe9098c2e8a2f91997de7c1103f74a8 This snippet demonstrates how to use the `embed!` macro to accept folders and get file contents using the file path. Note the trailing slash in the folder path. ```rust let asset = embed!("examples/public/".to_owned()); let index_html = asset("index.html".to_owned()).unwrap(); println!("{}", index_html); ``` -------------------------------- ### Basic Rust Embed Usage Source: https://pyrossh.dev/repos/rust-embed/commits/01d1ddafbae6a40494f9cbf1b973b982fbb60635 This example demonstrates the basic setup for using rust-embed with a custom derive macro. It shows how to define an Asset struct and implement the `RustEmbed` trait. ```rust #[macro_use] extern crate rust_embed; #[derive(RustEmbed)] struct Asset; fn main() { let data = Asset::get("hello.txt").unwrap(); println!("{}", std::str::from_utf8(&data).unwrap()); } ``` -------------------------------- ### Build Actix Example with Feature in Release Source: https://pyrossh.dev/repos/rust-embed Compiles the 'actix' example, enabling the 'actix' feature, in release mode. ```bash cargo build --example actix --features actix --release ``` -------------------------------- ### Axum Basic Static Handler Source: https://pyrossh.dev/repos/rust-embed/commits/f5dd61b4729775505a930e9e4fdbc70e98f0889d This example demonstrates a basic Axum route setup for serving static files from the 'dist' directory using rust-embed. It includes a handler for the root and index.html, and a catch-all route for files within the 'dist' path. ```rust use axum::{ body::boxed, http::{header, StatusCode, Uri}, response::{Html, IntoResponse, Response}, routing::{get, Router}, }; use rust_embed::RustEmbed; #[derive(RustEmbed)] struct Assets; #[tokio::main] async fn main() { let app = Router::new() .route("/", get(index_handler)) .route("/index.html", get(index_handler)) .route_service("/dist/*file", static_handler.into_service()) .fallback_service(get(not_found)); // Start listening on the given address. let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("listening on {}", addr); axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap(); } async fn index_handler() -> Html<&'static str> { Html("

Hello, World!

") } async fn static_handler(uri: Uri) -> Response { let path = uri.path().trim_start_matches('/'); if path.is_empty() || path == INDEX_HTML { return Assets::get(INDEX_HTML).map(boxed_file_response).unwrap_or_else(|| not_found()); } Assets::get(path).map(boxed_file_response).unwrap_or_else(not_found) } fn boxed_file_response(file: rust_embed::FileResponse) -> Response { boxed(Full::from(file.content)).map(|body| { Response::builder() .header(header::CONTENT_TYPE, file.mime.as_ref()) .body(body) .unwrap() }) } fn not_found() -> Response { Response::builder().status(StatusCode::NOT_FOUND).body(boxed(Full::from("Not Found"))).unwrap() } ``` -------------------------------- ### Run Rocket Example Source: https://pyrossh.dev/repos/rust-embed/commits/14d3817b2d742226a8d4575d087fe7fe3fd6f9a7 To run the Rocket example, you need to use the nightly toolchain and enable the 'nightly' feature flag. ```bash cargo +nightly run --example rocket --features nightly ``` -------------------------------- ### Complete actix-web example Source: https://pyrossh.dev/repos/rust-embed/files/examples/actix.rs/history This commit completes the example for Actix Web. ```rust Complete the example for actix-web ``` -------------------------------- ### Run Warp Example Source: https://pyrossh.dev/repos/rust-embed/commits/fba378e1cdd7cbbbc396ae6207af5aec85f70c5e Instructions for running the warp example are mentioned but no specific command is provided in this diff. -------------------------------- ### Axum SPA Server Setup Source: https://pyrossh.dev/repos/rust-embed/commits/b5e57f1efb75f8c7a14729c2b55375e0d6130225 This code sets up an Axum router to serve static files using `rust-embed` and starts the server on a specified address. It demonstrates the basic structure for a single-page application served statically. ```rust let app = Router::new().fallback(static_handler.into_service()); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("listening on {}", addr); axum::Server::bind(&addr).serve(app.into_service()).await.unwrap(); ``` -------------------------------- ### Install rust-embed Source: https://pyrossh.dev/repos/rust-embed/commits/26bf2b616733691738b6380ce97500cf5ffd607f Install the rust-embed tool using cargo. ```bash cargo install rust-embed ``` -------------------------------- ### Appveyor Install Script for Rust Source: https://pyrossh.dev/repos/rust-embed/commits/2c0015b02696e3fe73a5dda60c34425e7f2e0ae3 Installs the specified Rust toolchain using rustup and configures the PATH environment variable. Includes steps for installing nightly components and setting up MSYS paths. ```batch appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe ``` ```batch rustup-init -yv --default-toolchain %channel% --default-host %target% ``` ```batch set PATH=%PATH%;%USERPROFILE%\.cargo\bin ``` ```batch rustup install nightly ``` ```batch rustup component add rustfmt-preview --toolchain nightly ``` ```batch if defined MSYS_BITS set PATH=C:\msys64\mingw%MSYS_BITS%\bin;C:\msys64\usr\bin;%PATH% ``` ```batch rustc -vV ``` ```batch cargo -vV ``` -------------------------------- ### Run Poem Example Command Source: https://pyrossh.dev/repos/rust-embed/commits/524927fb4144080d216a926345edf3b31ba52f85 Instructions on how to run the Poem example using Cargo, specifying the necessary features. ```bash cargo run --example poem --features poem-ex ``` -------------------------------- ### Build Warp Example with Feature in Release Source: https://pyrossh.dev/repos/rust-embed Compiles the 'warp' example, enabling the 'warp-ex' feature, in release mode. ```bash cargo build --example warp --features warp-ex --release ``` -------------------------------- ### Add axum-spa Example to Cargo.toml Source: https://pyrossh.dev/repos/rust-embed/commits/00d74dbf43dfbbb69cd2bd7c02b17232acfe2221 This snippet shows how to register a new example named 'axum-spa' in the Cargo.toml file. This is necessary to include the example in your project's build process. ```toml [[example]] name = "axum-spa" path = "examples/axum-spa/main.rs" required-features = ["axum-ex"] ``` -------------------------------- ### Run Axum Example Command Source: https://pyrossh.dev/repos/rust-embed/commits/71d66a06be1c763ba82c0cf4fbc3c70a6cf830bb This snippet provides the command to run the Axum example, including the necessary feature flag. ```bash cargo run --example axum --features axum-ex ``` -------------------------------- ### Run Actix-web Example Source: https://pyrossh.dev/repos/rust-embed/commits/f5a60c8947f4c40b03a88e8724795a00ef1a660a Instructions for running the Actix-web example. No specific command is shown, but implies a 'cargo run' command with appropriate arguments. ```bash cargo run --example actix-web ``` -------------------------------- ### Run Warp Example Source: https://pyrossh.dev/repos/rust-embed/commits/14d3817b2d742226a8d4575d087fe7fe3fd6f9a7 To run the Warp example, use the standard cargo command and enable the 'warp-ex' feature flag. ```bash cargo run --example warp --features warp-ex ``` -------------------------------- ### Build Warp Example with Feature Source: https://pyrossh.dev/repos/rust-embed/commits/831f6eeddba2b16cbfb339a10d7a75a4bee545e9 Commands to build the warp example for rust-embed, enabling the 'warp-ex' feature. ```bash cargo build --example warp --features warp-ex cargo build --example warp --features warp-ex --release ``` -------------------------------- ### Basic Usage Example Source: https://pyrossh.dev/repos/rust-embed/commits/647cc1b44fd257d64f158db101061b7c5d32bfbb A basic Rust code example demonstrating the usage of rust-embed. ```rust struct Asset; impl Asset { fn get(path: &str) -> Option<&'static [u8]> { // ... implementation omitted ... None } } fn main() { // Example usage: // let html_content = Asset::get("index.html").unwrap(); } ``` -------------------------------- ### Example usage of Asset::get() with prefix Source: https://pyrossh.dev/repos/rust-embed/commits/c530a6ce47cfb5ac0f8a3367d22b69039a37910b This example demonstrates how to use the Asset::get() method with a prefixed file path. ```rust let index_html = Asset::get("prefix/index.html").unwrap(); ``` -------------------------------- ### Add Salvo Example to Cargo.toml Source: https://pyrossh.dev/repos/rust-embed/commits/121835e7229b040a081b5878fe6a1fc9e0fe0df7 This snippet shows the addition of a new example configuration for Salvo to the Cargo.toml file. It specifies the name, path, and required features for the Salvo example. ```toml [[example]] name = "salvo" path = "examples/salvo.rs" required-features = ["salvo-ex"] ``` -------------------------------- ### Build Axum Example with Features Source: https://pyrossh.dev/repos/rust-embed/commits/17ea0fd5abd7a01cd9dd2dae1c4795f307f36de5 Command to build the Axum example with specific features enabled. This is used in the CI workflow for testing. ```bash cargo build --example axum --features axum-ex ``` ```bash cargo build --example axum --features axum-ex --release ``` -------------------------------- ### Examples: Import RustEmbed directly Source: https://pyrossh.dev/repos/rust-embed/files/examples/actix.rs/history This commit changes the example to import RustEmbed directly, removing the need for `#[macro_use]`. ```rust examples: import RustEmbed directly instead of using #[macro_use] ``` -------------------------------- ### Add Rocket Example Source: https://pyrossh.dev/repos/rust-embed/files/examples/rocket.rs/history This snippet shows the initial addition of an example for integrating Rust Embed with the Rocket web framework. ```rust 44533ec6 — **pyros2097** ### ### 8 years ago ``` add rocket example ``` ``` -------------------------------- ### Build Rocket Example with Features Source: https://pyrossh.dev/repos/rust-embed/commits/6477b2acdd0cde2e5435f57d4bb500cf62e59cc7 This command builds the Rocket example for rust-embed, enabling the 'rocket' feature. It is used in CI for testing. ```bash cargo build --example rocket --features rocket ``` -------------------------------- ### Rust Embed Example with Compression Source: https://pyrossh.dev/repos/rust-embed/commits/01e8212e6a345a4a7f2de7e6f84600c7c675cc8e This is a basic usage example for rust-embed, demonstrating how to embed files. The 'compression' feature, when enabled, will compress these files. ```rust ```rust struct Asset; ``` ``` -------------------------------- ### Rust Embed Example with Rouille Source: https://pyrossh.dev/repos/rust-embed/commits/fe5ece6754d13c163813e150168fbbf738687acb This example demonstrates how to use rust-embed with the rouille web framework to serve static assets. It listens on localhost:8000 and serves files from the current directory. If a requested file is not found, it returns a 404 response with links to example files. ```rust #[macro_use] extern crate rouille; use rouille::Response; // TBD fn main() { println!("Now listening on localhost:8000"); rouille::start_server("localhost:8000", move |request| { { let response = rouille::match_assets(&request, "."); if response.is_success() { return response; } } Response::html( "404 error. Try README.md or \ src/lib.rs for example.", ).with_status_code(404) }); } ``` -------------------------------- ### Asset Struct Implementation Example Source: https://pyrossh.dev/repos/rust-embed/commits/b51c27dad00dfbf6d729664dbc5a43f3d2794387 Example of implementing the RustEmbed trait for an Asset struct, showing `get` and `iter` methods. ```rust impl RustEmbed for Asset { fn get(file_path: &str) -> Option> { // ... implementation details ... } fn iter() -> impl Iterator> { // ... implementation details ... } } ``` -------------------------------- ### Rust Embed Usage Example Source: https://pyrossh.dev/repos/rust-embed/commits/dc0fae9f0c68f45ac0b22c1f518f701ac9c29b2b Demonstrates how to retrieve embedded assets using the `get` method. This example shows the typical usage pattern for accessing files embedded at compile time. ```rust #[macro_use] extern crate rust_embed; #[derive(RustEmbed)] #[folder = "examples/public/"] struct Asset; fn main() { let index_html = Asset::get("index.html").unwrap(); println!("{:?}", std::str::from_utf8(index_html.as_ref())); } ``` -------------------------------- ### Add Rocket Example Source: https://pyrossh.dev/repos/rust-embed/files/examples/public/index_html/history This snippet represents a commit message for adding an example related to the Rocket web framework. ```git commit add rocket example ``` -------------------------------- ### Basic Server Setup with HelloWorld Source: https://pyrossh.dev/repos/rust-embed/commits/63f22834ae30e314f907e354cdb3d0bfd54e8fd2 This snippet shows a minimal HTTP server setup using the HelloWorld handler. It binds to a specific address and runs the server. ```rust fn main() { println!("Server running on 127.0.0.1:3000"); let addr = "127.0.0.1:3000".parse().unwrap(); let server = Http::new().bind(&addr, || Ok(HelloWorld)).unwrap(); server.run().unwrap(); } ``` -------------------------------- ### Actix.rs Example with Rust Embed Source: https://pyrossh.dev/repos/rust-embed/commits/451568cd0c93a9fd363829f54c17785e432bf4e8 This example demonstrates serving embedded files using rust-embed within an Actix web application. It includes setup for handling file requests and routing them to the embedded assets. Note the changes for Actix v4 compatibility, such as using `Responder` and simplified `HttpServer::new` configuration. ```rust use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use mime_guess::from_path; use rust_embed::RustEmbed; #[derive(RustEmbed)] #[folder = "examples/public/"] struct Asset; fn handle_embedded_file(path: &str) -> HttpResponse { match Asset::get(path) { Some(content) => HttpResponse::Ok() .content_type(from_path(path).first_or_octet_stream().as_ref()) .body(content.data.into_owned()), None => HttpResponse::NotFound().body("404 Not Found"), } } #[actix_web::get("/")] async fn index() -> impl Responder { handle_embedded_file("index.html") } #[actix_web::get("/dist/{_:.*}")] async fn dist(path: web::Path) -> impl Responder { handle_embedded_file(path.as_str()) } #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| App::new().service(index).service(dist)).bind("127.0.0.1:8000")?.run().await } ``` -------------------------------- ### Example Text File Content Source: https://pyrossh.dev/repos/rust-embed/files/examples/public/images/doc.txt This is a simple text file content example, likely used for testing file embedding. ```text Testing 1 2 3 ``` -------------------------------- ### Basic Usage of Embedded Assets Source: https://pyrossh.dev/repos/rust-embed/commits/89b83a82641cb20679cb647c882a374dc6c3b767 Access embedded assets using the `get` method on the struct declared with `#[derive(RustEmbed)]`. This example shows how to retrieve and print the content of 'index.html'. ```rust #![feature(attr_literals)] #[macro_use] extern crate rust_embed; #[macro_use] extern crate log; #[derive(RustEmbed)] #[folder("examples/public/")] struct Asset; fn main() { let index_html = Asset::get("index.html").unwrap(); println!("{:?}", std::str::from_utf8(&index_html)); } ``` -------------------------------- ### Running Examples in Development and Release Modes Source: https://pyrossh.dev/repos/rust-embed/files/README.md These commands demonstrate how to run the rust-embed examples. Use the first command for development mode (reading from the filesystem) and the second for release mode (reading from the binary). ```sh cargo run --example basic # dev mode where it reads from the fs cargo run --example basic --release # release mode where it reads from binary ``` -------------------------------- ### Appveyor CI Configuration (Deleted) Source: https://pyrossh.dev/repos/rust-embed/commits/88027902f5e0835a260da2e439b9bae39c5b3387 Previous Appveyor CI configuration for Rust projects, specifying build matrix for different toolchains and targets on Windows. It included setup for Rust installation and build commands. ```yaml # Appveyor configuration template for Rust using rustup for Rust installation # https://github.com/starkat99/appveyor-rust ## Operating System (VM environment) ## # Rust needs at least Visual Studio 2013 Appveyor OS for MSVC targets. os: Visual Studio 2015 # before repo cloning init: - git config --global core.symlinks true ## Build Matrix ## # This configuration will setup a build for each channel & target combination (12 windows # combinations in all). # # There are 3 channels: stable, beta, and nightly. # # Alternatively, the full version may be specified for the channel to build using that specific # version (e.g. channel: 1.5.0) # # The values for target are the set of windows Rust build targets. Each value is of the form # # ARCH-pc-windows-TOOLCHAIN # # Where ARCH is the target architecture, either x86_64 or i686, and TOOLCHAIN is the linker # toolchain to use, either msvc or gnu. See https://www.rust-lang.org/downloads.html#win-foot for # a description of the toolchain differences. # See https://github.com/rust-lang-nursery/rustup.rs/#toolchain-specification for description of # toolchains and host triples. # # Comment out channel/target combos you do not wish to build in CI. # # You may use the `cargoflags` and `RUSTFLAGS` variables to set additional flags for cargo commands # and rustc, respectively. For instance, you can uncomment the cargoflags lines in the nightly # channels to enable unstable features when building for nightly. Or you could add additional # matrix entries to test different combinations of features. environment: matrix: ### MSVC Toolchains ### # Stable 64-bit MSVC - channel: stable target: x86_64-pc-windows-msvc # # Stable 32-bit MSVC # - channel: stable ``` -------------------------------- ### Add Axum Example to Cargo.toml Source: https://pyrossh.dev/repos/rust-embed/commits/71d66a06be1c763ba82c0cf4fbc3c70a6cf830bb This snippet shows how to add a new example named 'axum' to your Cargo.toml file, specifying its path and required features. ```toml [[example]] name = "axum" path = "examples/axum.rs" required-features = ["axum-ex"] ``` -------------------------------- ### CI Workflow Steps: Setup and Checkout Source: https://pyrossh.dev/repos/rust-embed/commits/3115af1fed2663ec40ae84cd7f156e4dd125647c Specifies the initial steps in the CI workflow: setting up the Rust environment using a specific action and checking out the repository code. ```yaml steps: - uses: hecrj/setup-rust-action@v1 - uses: actions/checkout@master ``` -------------------------------- ### Include/Exclude Priority Example Source: https://pyrossh.dev/repos/rust-embed/commits/4527045ddf4d58e4baf8bf1f873c5fce5f96961e This example illustrates the priority of `exclude` over `include` when both are used. Here, `*.txt` is excluded, and `images/*` is included, resulting in only images being embedded. ```rust use rust_embed::Embed; #[derive(Embed)] #[folder = "examples/public/"] #[include = "images/*"] #[exclude = "*.txt"] struct ExcludePriorityAssets; ``` -------------------------------- ### Embedding Static Assets with Rust Embed Source: https://pyrossh.dev/repos/rust-embed/commits/91899db724707218e5843accbe39befdf0c95d79 Example demonstrating how to embed static assets using the `#[macro_use] extern crate embed_error;` and `#[macro_use] extern crate rust_embed;` macros. This setup is typically used at the crate root. ```rust #[macro_use] extern crate embed_error; #[macro_use] extern crate rust_embed; #[derive(RustEmbed)] #[folder = "static/"] struct Asset; fn main() { let data = Asset::get("hello.txt").unwrap(); println!("{}", String::from_utf8_lossy(&data)); } ``` -------------------------------- ### Rocket Web Server Example Source: https://pyrossh.dev/repos/rust-embed/commits/44533ec63ef0b9667908aa85fc0106240e53daaa This Rust code demonstrates how to set up a basic web server using the Rocket framework. It includes routes for serving static files and handling dynamic requests. ```rust use rocket::fs::NamedFile; use rocket::State; use rocket_contrib::databases::rocket_sync_db_pools::{diesel, r2d2}; use rocket_contrib::databases::Connection; #[database("my_db")] struct MyDatabase(Connection); #[get("/")] fn index() -> &'static str { "Hello, world!" } #[get("/static/")] async fn static_files(file: String) -> Option { NamedFile::open(format!("static/{}", file)).await.ok() } #[get("/users")] fn users(db: MyDatabase) -> Result { Ok(format!("Users: {:?}", users::table.load::(&*db)?)) } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![index, static_files, users]) .attach(MyDatabase::fairing()) } ``` -------------------------------- ### Examples: Improve actix-web example Source: https://pyrossh.dev/repos/rust-embed/files/examples/actix.rs/history This commit includes improvements to the Actix Web example. ```rust examples: improve actix-web example ``` -------------------------------- ### Get Embedded File (Dynamic Implementation) Source: https://pyrossh.dev/repos/rust-embed/commits/7ec554ea8d6ba45ab4bebfd80b3f13f8b9507d49 Provides the `get` method for dynamically retrieving embedded files. It calls the static `get` method of the identifier. ```Rust fn get(file_path: &str) -> ::std::option::Option<#crate_path::EmbeddedFile> { ``` -------------------------------- ### Add Warp Example to Cargo.toml Source: https://pyrossh.dev/repos/rust-embed/commits/07a1135dc69402c85e45802f7abbd7b067cfec61 This snippet demonstrates adding a new example named 'warp' to the Cargo.toml file. It includes the path to the example and the required feature 'warp'. ```toml [[example]] name = "warp" path = "examples/warp.rs" required-features = ["warp"] ``` -------------------------------- ### Add Rocket Example to Cargo.toml Source: https://pyrossh.dev/repos/rust-embed/commits/07a1135dc69402c85e45802f7abbd7b067cfec61 This snippet shows how to add a new example named 'rocket' to the Cargo.toml file. It specifies the path to the example and the required feature 'rocket'. ```toml [[example]] name = "rocket" path = "examples/rocket.rs" required-features = ["rocket"] ``` -------------------------------- ### Actix-web Example Source: https://pyrossh.dev/repos/rust-embed/commits/b36c90fcdba6c5463c46bfa85993388ac74eb279 Demonstrates a basic "Hello world!" application using the actix-web framework. This snippet is for the release build. ```Rust extern crate actix_web; use actix_web::{server, App, HttpRequest}; fn index(_req: HttpRequest) -> &'static str { "Hello world!" } fn main() { server::new(|| App::new().resource("/", |r| r.f(index))) .bind("127.0.0.1:8000") .unwrap() .run(); } ``` -------------------------------- ### Update dependencies for examples Source: https://pyrossh.dev/repos/rust-embed/files/examples/actix.rs/history This commit updates various dependencies used in the examples. ```rust Update dependencies for examples ``` -------------------------------- ### Running Web Framework Examples Source: https://pyrossh.dev/repos/rust-embed/files/README.md Examples for integrating rust-embed with popular Rust web frameworks like Actix, Rocket, Warp, Axum, Poem, and Salvo. Ensure you enable the corresponding feature flags. ```sh cargo run --example actix --features actix # https://github.com/actix/actix-web cargo run --example rocket --features rocket # https://github.com/SergioBenitez/Rocket cargo run --example warp --features warp-ex # https://github.com/seanmonstar/warp cargo run --example axum --features axum-ex # https://github.com/tokio-rs/axum cargo run --example poem --features poem-ex # https://github.com/poem-web/poem cargo run --example salvo --features salvo-ex # https://github.com/salvo-rs/salvo ``` -------------------------------- ### Axum Example with Rust Embed Source: https://pyrossh.dev/repos/rust-embed/commits/71d66a06be1c763ba82c0cf4fbc3c70a6cf830bb This example demonstrates setting up an Axum web server that serves static files using rust-embed. It includes handlers for different routes and a custom handler for static file serving. ```rust use std::convert::Infallible; use axum:: { body::{Bytes, Full}, handler::get, http::{header, Response, StatusCode, Uri}, response::{Html, IntoResponse}, routing::Router, }; use axum::handler::Handler; use mime_guess; use rust_embed::RustEmbed; use std::net::SocketAddr; #[tokio::main] async fn main() { // build our application with a route let app = Router::new() .route("/hello", get(helloworld)) // handle static files with rust_embed .route("/", get(index_handler)) .route("/index.html", get(index_handler)) .route("/dist/", static_handler.into_service()) .or(static_handler.into_service()); // run it let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("listening on {}", addr); axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap(); } async fn helloworld() -> Html<&'static str> { Html("

Hello, World!

") } // serve index.html from examples/public/index.html async fn index_handler() -> impl IntoResponse { static_handler("/index.html".parse::().unwrap()).await } // static_handler is a handler that serves static files from the async fn static_handler(uri: Uri) -> impl IntoResponse { let mut path = uri.path().trim_start_matches('/').to_string(); if path.starts_with("dist/") { path = path.replace("dist/", ""); } StaticFile(path) } #[derive(RustEmbed)] #[folder = "examples/public/"] struct Asset; pub struct StaticFile(pub T); impl IntoResponse for StaticFile where T: Into, { type Body = Full; type BodyError = Infallible; fn into_response(self) -> Response { let path = self.0.into(); match Asset::get(path.as_str()) { Some(content) => { let body = content.data.into(); let mime = mime_guess::from_path(path).first_or_octet_stream(); Response::builder().header(header::CONTENT_TYPE, mime.as_ref()).body(body).unwrap() } None => Response::builder().status(StatusCode::NOT_FOUND).body(Full::from("404")).unwrap(), } } } ``` -------------------------------- ### Update Warp Example Source: https://pyrossh.dev/repos/rust-embed/files/examples/warp.rs/history Updates the Warp example to work with version 0.2 of the framework. ```rust examples: update warp to 0.2 ``` -------------------------------- ### Add Warp Example Source: https://pyrossh.dev/repos/rust-embed/files/examples/warp.rs/history This snippet shows the initial addition of a Warp example to the project. ```rust Add warp example ``` -------------------------------- ### Axum SPA Example Fix Source: https://pyrossh.dev/repos/rust-embed/files/examples/axum-spa/main.rs/history This commit message indicates a fix for the axum-spa example. ```Rust Fix failing axum-spa example ``` -------------------------------- ### Run Salvo Example Source: https://pyrossh.dev/repos/rust-embed/commits/9df099dd717a2103764261e9bbae9cdc022a03a6 Instructions on how to run the Salvo example using Cargo. This command enables the 'salvo-ex' feature, which is necessary for compiling and running the Salvo-specific code. ```bash cargo run --example salvo --features salvo-ex ``` -------------------------------- ### Avoid Panics in Rocket Example Source: https://pyrossh.dev/repos/rust-embed/files/examples/rocket.rs/history This commit message indicates that panics have been avoided in the Rocket example. ```rust 087fb35a — **Bernardo** ### ### 7 years ago ``` avoid panics in rocket example ``` ``` -------------------------------- ### Prefix Example Update Source: https://pyrossh.dev/repos/rust-embed/commits/4527045ddf4d58e4baf8bf1f873c5fce5f96961e Illustrates the derive macro change for assets with a specified prefix. ```rust #[derive(Embed)] #[folder = "examples/public/"] #[prefix = "prefix/"] struct Asset; ``` -------------------------------- ### Build Rocket Example with Features and Release Mode Source: https://pyrossh.dev/repos/rust-embed/commits/6477b2acdd0cde2e5435f57d4bb500cf62e59cc7 This command builds the Rocket example for rust-embed in release mode, enabling the 'rocket' feature. It is used in CI for testing. ```bash cargo build --example rocket --features rocket --release ``` -------------------------------- ### Cargo.toml Configuration Example Source: https://pyrossh.dev/repos/rust-embed/commits/1dfe2c2da57ac03ca713c632719e5334d7255034 Example of a Cargo.toml file modification, specifically changing the 'categories' field. ```toml documentation = "https://docs.rs/rust-embed" repository = "https://github.com/pyros2097/rust-embed" license = "MIT" keywords = ["http", "rocket", "static", "web", "server"] categories = ["web-programming"] authors = ["pyros2097 "] edition = "2018" ``` -------------------------------- ### Fix Mime Guess Error in Warp Example Source: https://pyrossh.dev/repos/rust-embed/files/examples/warp.rs/history Addresses an error related to mime_guess in the Warp example. ```rust Fix mime_guess error in Warp example ``` -------------------------------- ### HTTP Server with Embedded Assets (Old) Source: https://pyrossh.dev/repos/rust-embed/commits/26bf2b616733691738b6380ce97500cf5ffd607f This example demonstrates a basic HTTP server using the hyper crate to serve embedded static assets. It handles requests for the root path and other files. ```rust extern crate hyper; use hyper::Server; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri::AbsolutePath; mod assets; fn handle_index(req: Request, res: Response) { match req.uri { AbsolutePath(ref path) => { println!("GET {:?}", &path); if &path[..] == "/" { res.send(&assets::examples_public_index_html).unwrap(); } else { res.send(assets::get(&path[1..path.len()]).unwrap()).unwrap(); } }, _ => { return; } } } fn main() { println!("Server running on 127.0.0.1:3000"); Server::http("127.0.0.1:3000").unwrap().handle(handle_index).unwrap(); } ``` -------------------------------- ### Shorter Axum Example Code Source: https://pyrossh.dev/repos/rust-embed/files/examples/axum-spa/main.rs/history This commit message indicates that the example code for Axum has been made shorter. ```Rust Shorter example code for axum ``` -------------------------------- ### Examples: Update actix-web to 2.0 Source: https://pyrossh.dev/repos/rust-embed/files/examples/actix.rs/history This commit updates the Actix Web example to use version 2.0. ```rust examples: update actix-web to 2.0 ``` -------------------------------- ### CI Workflow Steps: Running Tests and Builds Source: https://pyrossh.dev/repos/rust-embed/commits/3115af1fed2663ec40ae84cd7f156e4dd125647c Details the commands executed during the CI process, including code formatting checks, various test suites (lib, debug-embed, compression, interpolated_path), and building examples (basic, actix, warp) in both debug and release modes. ```yaml run: | cargo fmt --all -- --check cargo test --test lib cargo test --test lib --features "debug-embed" cargo test --test lib --release cargo test --test lib --features "compression" --release cargo test --test interpolated_path --features "interpolate-folder-path" cargo test --test interpolated_path --features "interpolate-folder-path" --release cargo build --example basic cargo build --example basic --release cargo build --example actix --features actix cargo build --example actix --features actix --release cargo build --example warp --features warp-ex cargo test --test lib --release cargo build --example basic --release cargo build --example actix --features actix --release cargo build --example warp --features warp-ex --release ``` -------------------------------- ### HTML for Axum SPA Example Source: https://pyrossh.dev/repos/rust-embed/commits/ae15c131571857dfa4ccd7bb7b5ec5ced0bcf38e The basic HTML structure for a single-page application served by the axum-spa example. ```html Single Page Application I'm the body! ``` -------------------------------- ### Axum Application Setup Source: https://pyrossh.dev/repos/rust-embed/commits/dba3f53e066df398a64ed538b42d169e3023eafa Sets up an Axum application to serve static files using rust-embed. It defines routes for the root, index.html, and a static file directory. ```rust use axum::{ body::boxed, handler::Handler, http::{header, StatusCode, Uri}, response::{Html, IntoResponse, Response}, routing::{get, Router}, }; use rust_embed::RustEmbed; use std::net::SocketAddr; #[derive(RustEmbed)] #[folder = "examples/static/"] struct Asset; async fn index_handler() -> Html<&'static str> { Html("

Hello Axum

index.html

dist/file.txt

") } struct StaticFile(T); impl IntoResponse for StaticFile where T: Into, { type Body = axum::body::BoxBody; type BodyError = std::convert::Infallible; fn into_response(self) -> Response { let path = self.0.into(); match Asset::get(path.as_str()) { Some(content) => { let body = boxed(Full::from(content.data)); let mime = mime_guess::from_path(path).first_or_octet_stream(); Response::builder().header(header::CONTENT_TYPE, mime.as_ref()).body(body).unwrap() } None => Response::builder().status(StatusCode::NOT_FOUND).body(boxed(Full::from("404"))).unwrap(), } } } #[tokio::main] async fn main() { // build our application with a route let app = Router::new() .route("/", get(index_handler)) .route("/index.html", get(index_handler)) .route("/dist/", static_handler.into_service()) .fallback(static_handler.into_service()); // run it let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("listening on {}", addr); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); } async fn static_handler(uri: Uri) -> StaticFile { StaticFile(uri.path().trim_start_matches('/').to_string()) } ``` -------------------------------- ### Compile Assets for Examples Source: https://pyrossh.dev/repos/rust-embed/commits/26bf2b616733691738b6380ce97500cf5ffd607f Use the rust-embed command-line tool to compile assets from a folder into a Rust file. ```bash rust-embed examples/public/ examples/assets.rs ``` -------------------------------- ### Include Specific Assets Example Source: https://pyrossh.dev/repos/rust-embed/commits/4527045ddf4d58e4baf8bf1f873c5fce5f96961e This example demonstrates deriving `Embed` while including only specific file types (HTML) and all files within an 'images' subdirectory. ```rust use rust_embed::Embed; #[derive(Embed)] #[folder = "examples/public/"] #[include = "*.html"] #[include = "images/*"] struct IncludeSomeAssets; ``` -------------------------------- ### Fix Rocket Example Index Page Source: https://pyrossh.dev/repos/rust-embed/files/examples/rocket.rs/history This commit message indicates a fix for the index page in the Rocket example. ```rust 970837f2 — **AzureMarker** ### ### 4 years ago ``` Fix rocket example index page ``` ``` -------------------------------- ### Rocket - Serving Embedded Files Source: https://pyrossh.dev/repos/rust-embed/commits/34dabb93db754e4625e0b52a4f1c0b4bfd4f21e9 This example demonstrates serving embedded static files using Rocket. It includes logic to extract file extensions and determine content types for responses. ```rust use rocket::response::{self, Response}; use rocket::http::ContentType; use std::path::PathBuf; use std::ffi::OsStr; use std::io::Cursor; #[derive(RustEmbed)] #[folder = "examples/public/"] struct Asset; #[get("/dist/")] fn dist<'r>(file: PathBuf) -> response::Result<'r> { let filename = file.display().to_string(); Asset::get(&filename).map_or_else( || Err(Status::NotFound), |d| { let ext = file .as_path() .extension() .and_then(OsStr::to_str) .ok_or(Status::new(400, "Could not get file extension"))?; let content_type = ContentType::from_extension(ext).ok_or(Status::new(400, "Could not get file content type"))?; response::Response::build().header(content_type).sized_body(Cursor::new(d)).ok() }, ) } ``` -------------------------------- ### Improve Embed and Rocket Example Source: https://pyrossh.dev/repos/rust-embed/files/examples/rocket.rs/history This commit message indicates improvements made to the existing embed and Rocket example. ```rust 1164bd35 — **pyros2097** ### ### 8 years ago ``` improve embed and rocket example ``` ```