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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Honoring If-Modified-Since lets you answer with a cheap 304 instead of resending unchanged bodies.
  2. 2Axum extractors and the IntoResponse tuple pattern let one handler return several distinct responses cleanly.
  3. 3Parsing untrusted headers with the ? operator on Option keeps the fallible path terse and safe.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Conditional GET caching in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code