Tutorial · 01

快速开始

从零到第一个可运行的 Web 应用。Zenith 默认仅启用最小核心,本教程带你逐步开启所需能力。

安装要求

  • Rust 1.97.1+(Stable,禁止 Nightly/Beta),edition 2024。
  • Linux 内核 5.4+:仅当启用 linux / ebpf / runtime 特性时需要。
  • libbpf 1.0+:启用 linux / ebpf 特性时需要。
  • Windows / macOS:无需特殊依赖,自动降级到 std::net
若只做协议解析或 Web 开发,无需 Linux 数据面。仅当要使用 AF_XDP / eBPF / io_uring 零拷贝能力时才需要 Linux 环境。

添加依赖

Cargo.toml 中按需引入。Zenith 是 feature-gated facade,默认只启用 api + core

Cargo.toml
# 最小类型层(仅 CanonicalRequest/Response) [dependencies] zenith = { path = "../zenith", default-features = false, features = ["api"] } # 仅 Web 框架(不拖入 AF_XDP / eBPF / 数据面) zenith = { path = "../zenith", default-features = false, features = ["web"] } # 完整生产协议栈 zenith = { path = "../zenith", features = ["full-stack"] } # 全部能力(含测试工具) zenith = { path = "../zenith", features = ["full"] }

最小依赖(仅类型定义)

src/main.rs
use zenith::api::{CanonicalRequest, Method}; fn main() { let mut req = CanonicalRequest::empty(); req.method = Method::Get; req.set_path("/api/users"); assert!(req.path() == "/api/users"); }

第一个 Web 应用

启用 web 特性后即可使用 App。编译期 Trie 路由实现运行期零开销分发。

src/main.rs · feature = web
use zenith::App; use zenith::api::{CanonicalRequest, CanonicalResponse}; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut app = App::new(); // GET /health → 204 app.get("/health", |_req, _params| { Ok(CanonicalResponse::new(204)) }); // GET /users/:id → 带路径参数 app.get("/users/:id", |req, params| { let id = params.get("id").unwrap_or("unknown"); let mut resp = CanonicalResponse::new(200); resp.set_body(format!("user: {{}}", id)); Ok(resp) }); app.run("0.0.0.0:8080") }

运行自带示例

Zenith 仓库自带多个示例,覆盖不同能力组合。运行前需确保已启用对应 feature(见 Cargo.toml 的 [[example]] 段的 required-features)。

terminal
# 最小 Web 服务器 cargo run --example hello_server # 完整生产协议栈(H1/H2/H3 + TLS + WAF + 代理) cargo run --example full_feature_server # L4 转发 / 中继 cargo run --example l4_test cargo run --example l4_relay_test # 指纹识别与阻断 cargo run --example fingerprint_block_test cargo run --example fingerprint_ext_test cargo run --example fingerprint_live_server # 自动降级 cargo run --example auto_degrade_test

验证运行

启动 hello_server 后,用 curl 验证三种协议与 TLS:

terminal
# HTTP/1.1 curl -i http://localhost:8080/health # HTTP/2(需启用 TLS) curl --http2 -k https://localhost:8443/ # HTTP/3(QUIC) curl --http3 -k https://localhost:8443/
下一步:理解设计定位请阅读 架构分层;按需选型请阅读 Feature 矩阵;编写业务逻辑请阅读 Web 框架指南