rust
46 lines · 8 steps
How a custom ClientIp extractor works in Axum
A custom Axum extractor resolves a client's IP from proxy headers, falling back to the raw socket address.
Explained by
highlit
1use std::net::{IpAddr, SocketAddr};
2
3use axum::extract::{ConnectInfo, FromRequestParts};
4use axum::http::request::Parts;
5use axum::http::{HeaderMap, StatusCode};
6
7pub struct ClientIp(pub IpAddr);
8
9impl<S> FromRequestParts<S> for ClientIp
10where
11 S: Send + Sync,
12{
13 type Rejection = (StatusCode, &'static str);
14
15 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
16 if let Some(ip) = ip_from_forwarded(&parts.headers) {
17 return Ok(ClientIp(ip));
18 }
19
20 if let Some(ip) = parts.headers.get("x-real-ip").and_then(parse_header) {
21 return Ok(ClientIp(ip));
22 }
23
24 let ConnectInfo(addr) = parts
25 .extensions
26 .get::<ConnectInfo<SocketAddr>>()
27 .copied()
28 .ok_or((StatusCode::INTERNAL_SERVER_ERROR, "missing connection info"))?;
29
30 Ok(ClientIp(addr.ip()))
31 }
32}
33
34fn ip_from_forwarded(headers: &HeaderMap) -> Option<IpAddr> {
35 headers
36 .get("x-forwarded-for")?
37 .to_str()
38 .ok()?
39 .split(',')
40 .map(str::trim)
41 .find_map(|candidate| candidate.parse::<IpAddr>().ok())
42}
43
44fn parse_header(value: &axum::http::HeaderValue) -> Option<IpAddr> {
45 value.to_str().ok()?.trim().parse().ok()
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing FromRequestParts lets you turn any request-derived value into a first-class handler argument.
- 2Resolving a client IP behind proxies means trusting forwarding headers first and treating the socket address as the last resort.
- 3Returning a typed Rejection keeps error handling explicit when required request context is missing.
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
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
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 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/how-a-custom-clientip-extractor-works-in-axum-explained-rust-ab1e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.