Skip to content

Instantly share code, notes, and snippets.

@xpe
Created January 22, 2024 13:54
Show Gist options
  • Save xpe/534061e82002ab2f4a840b6e1590fc9c to your computer and use it in GitHub Desktop.
Save xpe/534061e82002ab2f4a840b6e1590fc9c to your computer and use it in GitHub Desktop.
/src/server/extractors/headers/cp_connecting_ip.rs
use std::net::IpAddr;
use axum::http::HeaderMap;
#[derive(Debug, thiserror::Error)]
pub enum IpHeaderError {
#[error("`CF-Connecting-IP` header is missing")]
MissingHeader,
#[error("`CF-Connecting-IP` header contains invalid characters")]
InvalidChars,
#[error("Could not parse string into `std::net::IpAddr`")]
ParseFailure,
}
/// Extracts the value from the "CF-Connecting-IP" header.
pub fn cf_connecting_ip(headers: &HeaderMap) -> Result<IpAddr, IpHeaderError> {
headers
.get("CF-Connecting-IP")
.ok_or(IpHeaderError::MissingHeader)?
.to_str()
.map_err(|_| IpHeaderError::InvalidChars)?
.parse()
.map_err(|_| IpHeaderError::ParseFailure)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment