Actix-Web embed and serve static asset files
Example of how to embed a folder os static assets into the final binary and serve them on configured routes from actix-web.
First we need to declare the folder where the assets are located, I'll use a "assets"
folder relative to the crate root:
use rust_embed_for_web::RustEmbed;
#[derive(RustEmbed)]
#[folder = "assets/"]
struct Asset;
then we want to define a two services: a default handler for all kinds of files, straight from the asset folder, on a mountable path of choice, and then a special handler that explicitly serves the /favicon.ico
route which all browsers request by default:
// -snip--
.service(serve_asset)
.service(serve_favicon)
// -snip-
and this is how the handlers are made easily, including automatic mime-type, etag and last-modified headers, as well as doing automatic compression if it makes sense:
use actix_web::{get, web, Responder};
use actix_web_rust_embed_responder::{EmbedResponse, EmbedableFileResponse, IntoResponse};
#[get("/favicon.ico")]
async fn serve_favicon() -> impl Responder {
Asset::get("favicon.ico").into_response()
}
#[get("/assets/{name}")]
async fn serve_asset(name: web::Path<String>) -> EmbedResponse<EmbedableFileResponse> {
Asset::get(&name)
.into_response()
.use_compression(actix_web_rust_embed_responder::Compress::IfWellKnown)
}
Linked Technologies
What it's made of
![illustration of Actix-Web](/uploads/grimoire_technologies/13.thumbnail.webp)
Actix-Web
Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust. It runs on top of tokio and is probably the most mature rust web framework, with lots of available crates.
![illustration of Rust](/uploads/grimoire_technologies/11.thumbnail.webp)
Rust
A language empowering everyone to build reliable and efficient software. Futuristic swiss army knife and probably the most powerful mainstream technology today
Linked Categories
Where it's useful
![illustration of Backend Development](/uploads/grimoire_categories/6.thumbnail.webp)
Backend Development
Uncover the power behind the scenes of web services and applications, focusing on creating robust, scalable backend systems that support frontend experiences.