rustrust-warp

Serve static files in warp that are bundled in the executable?


I am writing an application using Warp with Rust for a while now, and I want to pack it into a standalone executable but the warp::fs::dir seems to load it from filesystem, as the name suggests.

Is there any way to bundle the static files as a warp filter? Or is there any other framework that supports this?

Just to clarify, by "bundle" i mean something like this:

fn get_file() -> &str {
    include_str!("file.html")
}

Solution

  • It seems like you are looking for static_dir macro from static_dir crate.

    Quoting from the documentation:

    Creates a Filter that serves a directory at the base $path joined by the request path.

    It behaves much like warp’s fs::dir, but instead of serving files from the filesystem at runtime, the directory to be served will be embedded into your binary at compile time.

    If the provided path is relative, it will be relative to the project root (as per the CARGO_MANIFEST_DIR environment variable).

    use static_dir::static_dir;
    use warp::Filter;
    
    // Matches requests that start with `/static`, and then uses the
    // rest of that path to lookup and serve a file from `/www/static`.
    let route = warp::path("static").and(static_dir!("/www/static"));
    
    // For example:
    // - `GET /static/app.js` would serve the file `/www/static/app.js`
    // - `GET /static/css/app.css` would serve the file `/www/static/css/app.css`