rust 49 lines · 7 steps

Serving embedded static files in Axum

Bundle static assets into the binary with rust_embed and serve them through Axum handlers with proper headers.

Explained by highlit
1use axum::{
2 body::Body,
3 http::{header, HeaderValue, StatusCode, Uri},
4 response::{IntoResponse, Response},
5 routing::get,
6 Router,
7};
8use rust_embed::RustEmbed;
9 
10#[derive(RustEmbed)]
11#[folder = "static/"]
12struct Assets;
13 
14pub fn router() -> Router {
15 Router::new()
16 .route("/favicon.ico", get(favicon))
17 .route("/robots.txt", get(robots))
18}
19 
20async fn favicon() -> Response {
21 serve_asset("favicon.ico")
22}
23 
24async fn robots() -> Response {
25 serve_asset("robots.txt")
26}
27 
28fn serve_asset(path: &str) -> Response {
29 match Assets::get(path) {
30 Some(asset) => {
31 let mime = mime_guess::from_path(path).first_or_octet_stream();
32 (
33 [
34 (
35 header::CONTENT_TYPE,
36 HeaderValue::from_str(mime.as_ref()).unwrap(),
37 ),
38 (
39 header::CACHE_CONTROL,
40 HeaderValue::from_static("public, max-age=86400"),
41 ),
42 ],
43 Body::from(asset.data),
44 )
45 .into_response()
46 }
47 None => StatusCode::NOT_FOUND.into_response(),
48 }
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Embedding assets into the binary with rust_embed removes the need to ship a separate files directory at deploy time.
  2. 2Guessing MIME types and setting cache headers lets a hand-rolled handler behave like a real static file server.
  3. 3A single shared helper keeps every asset route consistent in content type and caching behavior.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Serving embedded static files in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code