Skip to main content

Module uautil

Module uautil 

Source
Available on crate feature uautil only.
Expand description

User-Agent 工具: 机器人 / 浏览器识别、自定义特征、拦截中间件。

匹配规则为小写子串包含; 空 User-Agent 视为机器人、不是浏览器。特征列表是进程级全局状态, 由 RwLock 保护, 增删特征可与检测函数并发调用。

use rust_web_utils::uautil;

assert!(uautil::is_bot_user_agent("python-requests/2.31", false));
// allow_legitimate = true 时放行搜索引擎爬虫
assert!(!uautil::is_bot_user_agent("Mozilla/5.0 (compatible; Googlebot/2.1)", true));
assert!(uautil::is_browser_user_agent("Mozilla/5.0 (Windows NT 10.0) Chrome/130.0 Safari/537.36"));

开启 tower feature 后可用 BlockBotLayer / BrowserOnlyLayer 直接挂中间件。

完整文档: https://rust-web-utils.czl.net/docs/uautil

Structs§

BlockBotLayertower
拦截机器人的 tower 中间件: 命中时返回 403 纯文本, 默认文案 Bot access denied。
BrowserOnlyLayertower
仅允许浏览器访问的 tower 中间件: 非浏览器返回 403 纯文本, 默认文案 Browser access only
PatternRemover
add_* 返回的移除句柄; 调用 PatternRemover::remove 移除该特征, 直接丢弃句柄则特征一直保留
UaGuardtower
BlockBotLayer / BrowserOnlyLayer 包装后的服务; 响应体为 Either<内层响应体, Full<Bytes>>, 可直接用于 Axum Router::layer

Functions§

add_custom_bot_pattern
添加自定义机器人特征 (转小写); 返回的句柄可移除该特征
add_custom_browser_pattern
添加自定义浏览器特征 (转小写); 返回的句柄可移除该特征
add_legitimate_bot
添加自定义合法爬虫特征 (转小写); 返回的句柄可移除该特征
bot_patterns
当前机器人特征列表 (副本)
browser_patterns
当前浏览器特征列表 (副本)
is_bot
检测请求是否来自机器人; allow_legitimate 为 true 时放行合法搜索引擎爬虫
is_bot_user_agent
检测 User-Agent 字符串是否为机器人; 空 User-Agent 视为机器人。 allow_legitimate 为 true 时先匹配合法爬虫白名单, 命中即放行
is_browser
检测请求是否来自真实浏览器
is_browser_user_agent
检测 User-Agent 字符串是否为浏览器: 空串不是; 命中机器人特征不是 (合法爬虫同样不算浏览器); 其余命中浏览器特征即是
legitimate_patterns
当前合法爬虫特征列表 (副本)