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 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
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 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
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.