rust
53 lines · 7 steps
Handling raw byte uploads in Axum
An Axum route accepts a raw request body, enforces a size cap, persists it, and returns a typed JSON receipt.
Explained by
highlit
1use axum::{
2 body::Bytes,
3 extract::State,
4 http::StatusCode,
5 response::IntoResponse,
6 routing::post,
7 Json, Router,
8};
9use serde::Serialize;
10use tower_http::limit::RequestBodyLimitLayer;
11
12#[derive(Clone)]
13struct AppState {
14 store: std::sync::Arc<UploadStore>,
15}
16
17#[derive(Serialize)]
18struct UploadReceipt {
19 id: String,
20 size: usize,
21}
22
23const MAX_UPLOAD_BYTES: usize = 2 * 1024 * 1024;
24
25async fn upload_document(
26 State(state): State<AppState>,
27 body: Bytes,
28) -> Result<(StatusCode, Json<UploadReceipt>), StatusCode> {
29 if body.is_empty() {
30 return Err(StatusCode::BAD_REQUEST);
31 }
32
33 let id = state
34 .store
35 .persist(&body)
36 .await
37 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
38
39 Ok((
40 StatusCode::CREATED,
41 Json(UploadReceipt {
42 id,
43 size: body.len(),
44 }),
45 ))
46}
47
48pub fn documents_router(state: AppState) -> Router {
49 Router::new()
50 .route("/documents", post(upload_document))
51 .layer(RequestBodyLimitLayer::new(MAX_UPLOAD_BYTES))
52 .with_state(state)
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Axum extractors like State and Bytes turn request parsing into typed function arguments.
- 2Returning Result<T, StatusCode> lets a handler map failures to HTTP status codes ergonomically.
- 3Body-size limits belong in a middleware layer, not scattered through handler logic.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 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
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/handling-raw-byte-uploads-in-axum-explained-rust-0f15/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.