更具下面的内容修改这个错误 use crate::models::ip_model::IpInfo;
use crate::cache::ip_cache::{get_cached_ip, cache_ip};
use reqwest::Client;
use serde_json::Value;
use futures::future::BoxFuture;
use std::future::Future;
/// 请求 IP 信息服务入口(带缓存、容灾)
pub async fn get_ip_info(ip: &str) -> Result<IpInfo, String> {
if let Some(cached) = get_cached_ip(ip) {
return Ok(cached);
}
// 服务优先级:ipwho → ip-api → ipinfo
let providers: Vec<Box<dyn Fn(&str) -> BoxFuture<'static, Option<IpInfo>> + Send + Sync>> = vec![
Box::new(move |ip| Box::pin(query_from_ipwhois(ip))),
Box::new(move |ip| Box::pin(query_from_ip_api(ip))),
Box::new(move |ip| Box::pin(query_from_ipinfo(ip))),
];
for provider in providers {
if let Some(info) = provider(ip).await {
return Ok(info);
}
}
Err("🚫 所有服务失败".to_string())
}
pub async fn query_from_ipwhois(ip: &str) -> Option {
let url = format!("https://ipwho.is/{}", ip);
let json: Value = Client::new().get(&url).send().await.ok()?.json().await.ok()?;
if json.get("success")?.as_bool()? == false { return None; }
Some(IpInfo {
ip: json["ip"].as_str()?.to_string(),
country: json["country"].as_str().map(String::from),
region: json["region"].as_str().map(String::from),
city: json["city"].as_str().map(String::from),
isp: json.get("connection").and_then(|c| c.get("isp")).and_then(|v| v.as_str()).map(String::from),
provider: "ipwho.is".into(),
})
}
pub async fn query_from_ip_api(ip: &str) -> Option {
let url = format!("http://ip-api.com/json/{}?fields=status,country,regionName,city,isp,query", ip);
let json: Value = Client::new().get(&url).send().await.ok()?.json().await.ok()?;
if json["status"] != "success" { return None; }
Some(IpInfo {
ip: json["query"].as_str()?.to_string(),
country: json["country"].as_str().map(String::from),
region: json["regionName"].as_str().map(String::from),
city: json["city"].as_str().map(String::from),
isp: json["isp"].as_str().map(String::from),
provider: "ip-api.com".into(),
})
}
pub async fn query_from_ipinfo(ip: &str) -> Option {
let url = format!("https://ipinfo.io/{}/json", ip);
let json: Value = Client::new().get(&url).send().await.ok()?.json().await.ok()?;
Some(IpInfo {
ip: json["ip"].as_str()?.to_string(),
country: json["country"].as_str().map(String::from),
region: json["region"].as_str().map(String::from),
city: json["city"].as_str().map(String::from),
isp: json["org"].as_str().map(String::from),
provider: "ipinfo.io".into(),
})
}