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 std::sync::Arc; use std::time::Duration; use axum::{
Long-polling with Axum and Tokio Notify
long-polling
concurrency
shared-state
Advanced
8 steps
typescript
import { Controller, Get, Param, Query, Redirect, NotFoundException } from '@nestjs/common'; import { LinksService } from './links.service'; @Controller('links')
Handling HTTP redirects in NestJS
redirects
routing
decorators
Intermediate
7 steps
php
final class Route { private string $regex; private array $paramNames = [];
Compiling route patterns into regex in PHP
routing
regex
parsing
Intermediate
8 steps
rust
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::thread;
A round-robin worker pool in Rust
concurrency
thread-pool
channels
Intermediate
7 steps
rust
use std::fs::File; use std::io::{self, Read}; use std::path::Path;
Streaming a SHA-256 hash of a file in Rust
hashing
buffered-io
streaming
Intermediate
5 steps
rust
use axum::{ extract::State, http::StatusCode, Json,
Idempotent webhook handling in Axum
deduplication
idempotency
shared-state
Intermediate
8 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.