# rust-web-utils
CZL Rust Web 服务公共工具库, 与 Go 版 [go-web-utils](https://github.com/woodchen-ink/go-web-utils) 语义对齐: 同一产品无论后端用 Go 还是 Rust, 前端拿到的响应结构、Cookie、缓存头、IP 判定都一致。
完整文档: https://rust-web-utils.czl.net
## 模块
| `iputil` | 客户端真实 IP (主流 CDN / 代理头)、可信代理 `TrustedProxies`、IP 校验与 CIDR 匹配 |
| `uautil` | 机器人 / 浏览器识别、自定义特征、tower 拦截中间件 |
| `resputil` | 统一 JSON 响应 `{ code, data, msg }`, 空数据永不返回 `null` |
| `timex` | 业务时区显式初始化、自然日 / 周 / 月边界、RFC3339 |
| `cookieutil` | 安全默认值的认证 Cookie (强制 HttpOnly)、CSRF double-submit |
| `cronutil` | 空轮指数退避、单实例防重叠、去抖聚合队列 (Tokio) |
| `nextstatic` | Next.js 15/16 静态导出托管: RSC 头、动态路由回退、防软 404、SEO 注入 |
基于 `http` crate 的通用类型实现, 不绑定框架; `axum` feature 提供 `IntoResponse` 与 `ConnectInfo` 支持, `tower` feature 提供中间件。
## 安装
```toml
[dependencies]
rust-web-utils = { git = "https://github.com/woodchen-ink/rust-web-utils", tag = "v0.1.0", features = ["axum", "tower"] }
```
只用部分模块:
```toml
rust-web-utils = { git = "https://github.com/woodchen-ink/rust-web-utils", tag = "v0.1.0", default-features = false, features = ["iputil", "resputil", "axum"] }
```
最低 Rust 版本 1.88。
## 示例
```rust
use std::net::SocketAddr;
use axum::{Router, routing::get};
use rust_web_utils::{nextstatic::{Config, NextStatic}, resputil, timex, uautil::BlockBotLayer};
#[tokio::main]
async fn main() {
timex::must_init("Asia/Shanghai");
let api = Router::new()
.route("/health", get(|| async { resputil::ok(()) }))
.layer(BlockBotLayer::new(false));
let web = NextStatic::new(Config { trailing_slash: true, ..Config::new("./web/out") }).expect("load web/out");
let app = Router::new().nest("/api", api).fallback_service(web);
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();
}
```
## 开发
```bash
cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features
```
文档站在 `docs/` (Next.js + Fumadocs 静态导出), 部署到 Cloudflare Workers: `cd docs && npm run deploy`。
## License
MIT