rust
50 lines · 7 steps
Custom Axum responses with per-user ETags
A generic wrapper that serializes any payload to JSON and attaches a user-specific ETag by implementing IntoResponse.
Explained by
highlit
1use axum::body::Bytes;
2use axum::http::{header, HeaderValue, StatusCode};
3use axum::response::{IntoResponse, Response};
4use serde::Serialize;
5use sha2::{Digest, Sha256};
6
7pub struct Personalized<T> {
8 user_id: i64,
9 payload: T,
10}
11
12impl<T> Personalized<T> {
13 pub fn new(user_id: i64, payload: T) -> Self {
14 Self { user_id, payload }
15 }
16}
17
18impl<T: Serialize> IntoResponse for Personalized<T> {
19 fn into_response(self) -> Response {
20 let body = match serde_json::to_vec(&self.payload) {
21 Ok(bytes) => Bytes::from(bytes),
22 Err(err) => {
23 return (
24 StatusCode::INTERNAL_SERVER_ERROR,
25 format!("serialization failed: {err}"),
26 )
27 .into_response();
28 }
29 };
30
31 let mut hasher = Sha256::new();
32 hasher.update(self.user_id.to_le_bytes());
33 hasher.update(&body);
34 let digest = hasher.finalize();
35
36 let etag = format!("\"{:x}\"", digest);
37 let etag = HeaderValue::from_str(&etag)
38 .unwrap_or_else(|_| HeaderValue::from_static("\"invalid\""));
39
40 (
41 [
42 (header::CONTENT_TYPE, HeaderValue::from_static("application/json")),
43 (header::ETAG, etag),
44 (header::CACHE_CONTROL, HeaderValue::from_static("private, max-age=0")),
45 ],
46 body,
47 )
48 .into_response()
49 }
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing IntoResponse lets you package serialization, headers, and status into a reusable return type your handlers can hand back directly.
- 2Folding the user id into the ETag hash keeps caches from serving one user's personalized body to another.
- 3Returning early with a status-and-message tuple gives you clean error responses that also satisfy IntoResponse.
Related explainers
rust
use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use axum::body::Body;
A maintenance-mode gate in Axum
middleware
shared-state
atomics
Intermediate
7 steps
rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; use std::sync::Arc;
Batch inserts with per-item status in Axum
batch-processing
error-handling
serde
Intermediate
8 steps
rust
use std::time::Duration; #[derive(Debug, PartialEq)] pub enum ParseDurationError {
Parsing duration strings safely in Rust
parsing
error-handling
checked-arithmetic
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
rust
use std::time::Duration; #[derive(Debug, Clone, Copy)] pub struct LatencyStats {
Computing latency percentiles in Rust
percentiles
interpolation
closures
Intermediate
6 steps
python
import hashlib from collections import defaultdict from pathlib import Path
Finding duplicate files by size then hash
hashing
file-io
deduplication
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/custom-axum-responses-with-per-user-etags-explained-rust-bbed/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.