# `static_file_util` `static_file_util` is a utility crate for generating and managing static files in Rust applications. It simplifies the process of embedding static assets into your project and automatically provides hashes for cache-busting, making it ideal for web applications and similar use cases. Check the [axum example](https://github.com/crabby-utils/static_file_util/blob/main/examples/axum/src/main.rs) for details of how to use this in a web application to serve static files, like images or CSS. ## Features - Define static files with ease using a single macro. - Automatically computes content hashes, allowing for effective cache control. - Provides a convenient interface to access static files at runtime. ## Installation Add `static_file_util` as a dependency in your `Cargo.toml`: ```toml [dependencies] static_file_util = "0.1.0" lazy_static = "1.4" # Required dependency for lazy static initialization mime = "0.3" # For handling MIME types [build-dependencies] static_file_util = "0.1.0" ``` ## Usage This usage example demonstrates the steps required to make use of `static_file_util`. 1. The file hashes are calculated using a `build.rs` script. 2. The files are defined using the `static_files!` macro. 3. The `.name` property is used to access the generated file names (including the hash). 4. The StaticFile struct is utilised to resolve the files and serve up the content with the correct MIME type. ### Environment Variable for Hashing In order to generate unique names for each file, a `build.rs` script can be used to generate content hashes during the build process. These hashes are passed as environment variables to the main code. Here's an example of a `build.rs` script that works with `static_file_util`: ```rust use static_file_util::process_file; fn main() { process_file("images/logo.svg", "logo_svg_HASH"); process_file("css/styles.css", "styles_css_HASH"); } ``` The `process_file` function reads the file contents, generates a hash, and sets it as an environment variable that the macro uses during compilation. It is recommended to add this `build.rs` script to your project in order to automatically generate the environment variables required to define static files. ### Define Static Files Use the `static_files!` macro to define your static assets. This macro allows you to embed files directly into your binary, providing easy access to their contents and metadata. Here's an example of how to use `static_file_util` in your project: ```rust use static_file_util::static_files; static_files!( (logo_svg, "../images/logo.svg", mime::IMAGE_SVG), (styles_css, "../css/styles.css", mime::TEXT_CSS), ); fn main() { // Example of using the generated file names in an HTML template let styles = format!("/static/{}", styles_css.name); let logo_src = format!("/static/{}", logo_svg.name); let html_template = format!(r#"