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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Embedding assets into the binary with rust_embed removes the need to ship a separate files directory at deploy time.
- 2Guessing MIME types and setting cache headers lets a hand-rolled handler behave like a real static file server.
- 3A single shared helper keeps every asset route consistent in content type and caching behavior.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/serving-embedded-static-files-in-axum-explained-rust-b890/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.