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;

#[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--
		// -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};

async fn serve_favicon() -> impl Responder {

async fn serve_asset(name: web::Path<String>) -> EmbedResponse<EmbedableFileResponse> {

Linked Technologies

What it's made of

illustration of 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

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
Backend Development

Uncover the power behind the scenes of web services and applications, focusing on creating robust, scalable backend systems that support frontend experiences.