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 axum::{ body::Body, extract::State, http::{header, StatusCode},
Streaming NDJSON from Postgres in Axum
streaming
backpressure
async
Advanced
9 steps
rust
use once_cell::sync::Lazy; use regex::Regex; static LOG_LINE: Lazy<Regex> = Lazy::new(|| {
Parsing access logs with a lazy regex in Rust
regex
lazy-initialization
parsing
Intermediate
7 steps
rust
use axum::{ extract::State, response::sse::{Event, KeepAlive, Sse}, Json,
Proxying an SSE chat stream in Axum
server-sent-events
streaming
async-generators
Advanced
10 steps
rust
use std::collections::HashMap; fn decode_component(input: &str) -> String { let bytes = input.as_bytes();
Parsing a URL query string in Rust
url-encoding
byte-parsing
iterators
Intermediate
8 steps
rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FileKind { Png, Jpeg,
Detecting file types by magic bytes in Rust
pattern-matching
byte-slices
lookup-table
Intermediate
7 steps
go
func (h *ExportHandler) BulkExport(c *gin.Context) { projectID := c.Param("projectID") reports, err := h.reports.ListByProject(c.Request.Context(), projectID)
Streaming a ZIP download in Gin
streaming
zip-archive
http-headers
Intermediate
8 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.