grweb
基于 gorust 协程运行时的高性能 Rust Web 框架,结合 Go 风格的并发模型与 Rust 的零成本抽象。
特性
- Go 风格并发 — 基于 gorust 的 goroutine-per-connection 模型,每个连接一个轻量级协程
- 树形路由 — 支持路径参数
/hello/:name,精确匹配优先于参数匹配 - 中间件链 — 零堆分配的洋葱模型中间件,内置 Logger / Recovery / CORS
- TOML 配置 — 所有参数通过
config.toml统一管理,均有合理默认值 - 低 CPU 空闲 — 阻塞 I/O + 指数退避调度,空闲 CPU < 1%
- 高性能 — release 模式 ~89,000 QPS(与 gorust 原生示例差距 < 3%)
快速开始
1. 添加依赖
[]
= { = "http://github.com/WLmutou/grweb.git" }
= "1.0"
= "0.10"
2. 编写应用
use ;
3. 运行
RUST_LOG=info
访问 http://127.0.0.1:9030/hello/grweb 看到 Hello, grweb!
配置文件
创建 config.toml(所有字段均可选):
[]
= "127.0.0.1" # 监听地址(默认 127.0.0.1)
= 9030 # 监听端口(默认 9030)
= 4 # 工作线程数(默认 CPU 核心数)
= 8192 # 读缓冲区字节数(默认 8192)
= true # TCP_NODELAY(默认 true)
= 5 # Keep-Alive 超时秒数(默认 5)
= "public" # 静态文件目录(默认 public)
[]
= "error" # trace | debug | info | warn | error(默认 info)
[]
= ["*"]
= ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
= ["Content-Type"]
加载配置:
use AppConfig;
let config = load.expect;
// 日志级别自动设置
unsafe
init;
// CORS 从配置读取
router.use_middleware;
// 服务器从配置构建
let server = new;
路由
基本路由
router.get;
router.post;
router.put;
router.delete;
路径参数
以 : 前缀定义参数,通过 ctx.param() 获取:
router.get;
router.get;
路由优先级
精确匹配优先于参数匹配。例如同时注册 /user/me 和 /user/:id:
router.get;
router.get;
中间件
内置中间件
| 中间件 | 说明 |
|---|---|
LoggerMiddleware |
记录请求方法、路径、状态码、耗时 |
RecoveryMiddleware |
捕获 handler panic,返回 500 |
CORSMiddleware |
添加跨域响应头 |
自定义中间件
实现 Middleware trait:
use ;
;
// 注册
router.use_middleware;
中间件链执行顺序
注册顺序即执行顺序(洋葱模型):
请求 → Logger → Recovery → CORS → Handler → CORS → Recovery → Logger → 响应
Context API
Response API
// 基础响应
new
new
// 快捷方法
html // Content-Type: text/html
json // Content-Type: application/json
not_found // 404
internal_error // 500
// 自动类型转换
"hello" → html
"hello".to_string → html
vec! → new
// 自定义响应头
let mut resp = html;
resp.headers.push;
静态文件服务
通过 serve_static 将 URL 前缀映射到本地目录:
// 将 /static/* 映射到 ./public 目录
router.serve_static;
访问 http://127.0.0.1:9030/static/css/style.css → ./public/css/style.css
安全特性:自动防止路径穿越攻击(../ 等),不存在的文件返回 404。
MIME 类型:自动根据文件扩展名设置 Content-Type,支持 HTML/CSS/JS/JSON/图片/字体/视频/音频等 20+ 种类型。
表单数据解析
自动识别 application/x-www-form-urlencoded 和 multipart/form-data:
router.post;
URL 解码:自动处理 %XX 和 +(空格)解码。
multipart 支持:自动提取 boundary、解析 Content-Disposition 头中的 name 字段。
WebSocket
通过 router.websocket() 注册 WebSocket 路由,handler 接收 WebSocket 对象进行双向通信:
use ;
router.websocket;
WebSocket API:
协议支持:RFC 6455,支持分片消息重组、ping/pong 心跳、close 帧(含状态码)。
性能
wrk 压测(4 线程 / 100 连接 / 5 秒,AMD Ryzen):
| 服务 | QPS | 延迟 | 备注 |
|---|---|---|---|
| gorust web_server_yield | 89,300 | 626μs | 无路由/无解析/预构建响应 |
| gorust web_server_router | 72,900 | 816μs | HashMap 路由 |
| grweb | 88,000 | 660μs | 树形路由 + 3 层中间件 + 完整解析 |
空闲 CPU:< 1%
features
- Keep-Alive 连接复用
- 请求头解析(Cookie / Authorization)
- 静态文件服务(MIME 自动检测 / 路径穿越防护)
- WebSocket 支持(RFC 6455 / 分片重组 / ping-pong)
- 表单数据解析(urlencoded / multipart)
- 连接池管理
- HTTPS 支持
- 优雅降级和限流
- 测试用例(未见 tests/ 目录)
License
MIT © 2026 WLmutou