IP 地理与自治系统查询
属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io
启动时加载本地 MaxMind DB(.mmdb)格式地址库,提供零网络延迟的国家、一级行政区与自治系统号(ASN)查询、客户端地址自动提取器 IpInfo、按国家放行的路由门禁中间件 require_country,以及可选的后台定时下载校验与原子热替换。
快速接入#
在 Cargo.toml 开启主包 kxed 的 ip 特性(需要后台自动下载热更新词库时改开 ip-update,自动包含 http-client;独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["ip"] }):
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["ip", "security"] }在应用配置文件中指定本地 .mmdb 库文件路径:
[ip]
database = "data/GeoLite2-City.mmdb"在应用中注册 IpPlugin::new(),即可在业务 Procedure 中查询任意 IP,或在路由上挂载国家白名单门禁:
use kxed::plugins::ip::{require_country, IpInfo, IpPlugin};
use kxed::plugins::security::SecurityPlugin;
use kxed::prelude::*;
#[query(name = "geo.current", public, get = "/api/geo")]
pub async fn current_geo(ctx: &AppCtx) -> Result<Option<String>, AppErr> {
let Some(ip) = ctx.client_ip() else {
return Ok(None);
};
Ok(ctx.ip_info(ip)?.and_then(|info| info.country))
}
async fn region_banner(info: IpInfo) -> String {
info.region.unwrap_or_else(|| "global".to_owned())
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.plugin(SecurityPlugin::new())
.plugin(IpPlugin::new())
.routes(|router| {
router.route("/banner", get(region_banner));
router.group("/in-only", |g| {
g.layer(require_country(&["IN"]));
g.route("/promo", get(|| async { "eligible" }));
});
})
.run()
.await
}核心用法#
子 crate 可编译用法示例:
use axum::routing::get;
use axum::Router;
use kxed_core::{AppCtx, AppErr, ClientIp};
use kxed_plugins::ip::{require_country, AppCtxIp, IpInfo};
async fn welcome(ctx: AppCtx, ClientIp(ip): ClientIp) -> Result<String, AppErr> {
let country = ctx.ip_info(ip)?.and_then(|info| info.country);
Ok(country.unwrap_or_else(|| "unknown".to_owned()))
}
async fn region(info: IpInfo) -> String {
info.region.unwrap_or_default()
}
async fn known(info: Option<IpInfo>) -> &'static str {
if info.is_some() { "listed" } else { "not in the database" }
}
fn routes() -> Router {
Router::new()
.route("/welcome", get(welcome))
.route("/region", get(region))
.route("/known", get(known))
.route("/event/join", get(|| async { "joined" }).layer(require_country(&["IN"])))
}查询字段与提取规则#
兼容 MaxMind GeoLite2 / GeoIP2 与 DB-IP Lite 的标准字段结构(各字段是否有值取决于所载入的 .mmdb 库种类):
IpInfo 字段 | 含义 | 支持该字段的库类型 |
|---|---|---|
country | 大写两位国家代码(ISO 3166-1 alpha-2,如 "IN"、"US",取所在地 country.iso_code) | Country、City、Enterprise |
region | 一级行政区代码(ISO 3166-2 子代码,如 "KA",取 subdivisions[0]) | City、Enterprise |
asn | 自治系统编号(u32) | ASN、ISP、Enterprise |
- 方法与提取器差异:
ctx.ip_info(ip)?在内网或未收录网段返回Ok(None)(IPv4-mapped IPv6 自动按内嵌 IPv4 查询,记录损坏返 500ip_lookup_failed);handler 参数IpInfo自动读取ClientIp(配合SecurityPlugin还原代理后真实客户端 IP),未收录时返回全None的IpInfo,需区分是否收录时提取Option<IpInfo>。 - 国家门禁
require_country(&["IN", "SG"]):忽略大小写比对两位 ASCII 国家码,不在白名单内或查不到国家统一返回 403ip_country_denied。
后台热更新(ip-update)#
启用 ip-update 特性、注册 HttpClientPlugin 并配置 ip.update.url(须直接返回解压后的 .mmdb 二进制且 <= 16 MiB)后,后台受管任务每隔 ip.update.interval 自动拉取新库:先写入同目录临时文件 fsync 并完整校验 verify() 搜索树,通过后原子 rename 覆盖磁盘并无锁替换内存句柄。中途下载失败或文件损坏只写脱敏 warn,线上查询全程不中断、不读到半截数据。
配置#
| 键 | 缺省 | 范围与含义 |
|---|---|---|
ip.database | 空 | 必填,启动前必须已存在的本地 .mmdb 文件路径 |
ip.update.url | 空 | 为空不开启热更新;非空为 .mmdb 下载 URL(按密钥脱敏,不在 config show 或错误中回显) |
ip.update.interval | 24h | 两次热更新下载之间的等待间隔,范围 10ms..=365d |
多实例与测试说明#
- 多实例独立加载:每个实例在内存中独立持有一份词库(内存占用约等于文件大小);同机多实例共用同一路径开启热更新时各自写独立临时文件再原子
rename,互不破坏;若上游有下载频次配额,建议通过内网对象存储或镜像站统一分发。 - 内置测试夹具:
tests/data/目录附带官方小型测试.mmdb样本,单测可通过ConfigLoader::testing().with_override("ip.database", path)直接加载验证。