mycommon-utils 0.2.1

Common utilities library for database operations, Redis caching and system utilities
Documentation
use axum::http::HeaderMap;


pub fn get_remote_ip(header: HeaderMap) -> String {
    let ip = match header.get("X-Forwarded-For") {
        Some(x) => {
            let mut ips = x.to_str().unwrap_or("").split(','); // 处理可能的 None
            let ip = ips.next().unwrap_or("").trim().to_string();
            if ip.is_empty() {
                "Unknown".to_string()
            } else {
                ip
            }
        }
        None => match header.get("X-Real-IP") {
            Some(x) => {
                let ip = x.to_str().unwrap_or("").to_string(); // 处理可能的 None
                if ip.is_empty() {
                    "Unknown".to_string()
                } else {
                    ip
                }
            }
            None => {
                // 如果没有代理,尝试从 remote_addr 获取 IP
                header.get("remote_addr")
                    .and_then(|x| x.to_str().ok())
                    .unwrap_or("Unknown")
                    .to_string()
            }
        },
    };
    ip
}