rust
54 lines · 7 steps
Conditional GET caching in Axum
An Axum handler that returns 304 Not Modified when a client's cached article is still fresh.
Explained by
highlit
1use axum::{
2 extract::State,
3 http::{header, HeaderMap, StatusCode},
4 response::{IntoResponse, Response},
5};
6use chrono::{DateTime, Utc};
7use std::sync::Arc;
8
9#[derive(Clone)]
10struct AppState {
11 articles: Arc<ArticleRepo>,
12}
13
14pub async fn get_article(
15 State(state): State<AppState>,
16 axum::extract::Path(slug): axum::extract::Path<String>,
17 headers: HeaderMap,
18) -> Response {
19 let article = match state.articles.find(&slug).await {
20 Some(article) => article,
21 None => return StatusCode::NOT_FOUND.into_response(),
22 };
23
24 let last_modified = article.updated_at;
25
26 if let Some(since) = parse_if_modified_since(&headers) {
27 if last_modified.timestamp() <= since.timestamp() {
28 return (StatusCode::NOT_MODIFIED, http_date_headers(last_modified)).into_response();
29 }
30 }
31
32 (
33 StatusCode::OK,
34 http_date_headers(last_modified),
35 axum::Json(article),
36 )
37 .into_response()
38}
39
40fn parse_if_modified_since(headers: &HeaderMap) -> Option<DateTime<Utc>> {
41 let raw = headers.get(header::IF_MODIFIED_SINCE)?.to_str().ok()?;
42 DateTime::parse_from_rfc2822(raw)
43 .map(|dt| dt.with_timezone(&Utc))
44 .ok()
45}
46
47fn http_date_headers(when: DateTime<Utc>) -> HeaderMap {
48 let mut headers = HeaderMap::new();
49 let value = when.format("%a, %d %b %Y %H:%M:%S GMT").to_string();
50 if let Ok(header_value) = value.parse() {
51 headers.insert(header::LAST_MODIFIED, header_value);
52 }
53 headers
54}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Honoring If-Modified-Since lets you answer with a cheap 304 instead of resending unchanged bodies.
- 2Axum extractors and the IntoResponse tuple pattern let one handler return several distinct responses cleanly.
- 3Parsing untrusted headers with the ? operator on Option keeps the fallible path terse and safe.
Related explainers
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
rust
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::path::Path;
Parsing INI files in Rust
parsing
file-io
hashmap
Intermediate
9 steps
rust
use axum::{ extract::{Path, Query}, http::Uri, response::{IntoResponse, Redirect},
Building HTTP redirect handlers in Axum
redirects
extractors
url-handling
Intermediate
7 steps
rust
use axum::{ body::Body, extract::MatchedPath, http::{Request, StatusCode},
An admin route guard in Axum middleware
middleware
authorization
request-extensions
Intermediate
7 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/conditional-get-caching-in-axum-explained-rust-5817/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.