22 个版本
0.9.0-alpha.2 | 2020 年 1 月 7 日 |
---|---|
0.8.0 | 2019 年 12 月 21 日 |
0.7.18 | 2019 年 11 月 9 日 |
0.7.8 | 2019 年 6 月 20 日 |
#1301 在 HTTP 服务器
38 每月下载量
在 6 个 Crates 中使用(通过 thruster-core)
7KB
126 行
Thruster

快速直观的 Rust Web 框架
没有时间阅读文档?查看
✅ 在稳定版上运行 ✅ 运行速度快 ✅ 不使用 unsafe
功能
动机
Thruster 是一个 Web 框架,旨在让开发者在项目之间和团队之间保持高效和一致性。其目标是
- 高性能
- 简单
- 直观
Thruster 还
- 不使用
unsafe
- 在稳定 Rust 上运行
快速
Thruster 可以与不同的服务器后端一起运行,并在其之上提供了一个包装良好的层。这意味着它可以跟上 Hyper、Actix 或甚至 ThrusterServer(一个自制的 http 引擎)等类似技术的最新和最佳变化。
直观
基于 Koa 和 Express 等框架,Thruster 努力成为一个令人愉悦的开发工具。
示例
要运行示例,请执行以下命令:cargo run --example <example-name>
。例如,cargo run --example hello_world
然后打开 https://127.0.0.1:4321/
基于中间件
使新的async await代码能够工作的是,通过使用#[middleware_fn]
属性(这使中间件与Thruster构建的稳定futures版本兼容)来指定中间件函数,然后在实际路由中使用m!
宏。
使用async await的一个简单示例:
use std::boxed::Box;
use std::future::Future;
use std::pin::Pin;
use std::time::Instant;
use thruster::{App, BasicContext as Ctx, Request};
use thruster::{m, middleware_fn, MiddlewareNext, MiddlewareResult, Server, ThrusterServer};
#[middleware_fn]
async fn profile(context: Ctx, next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
let start_time = Instant::now();
context = next(context).await;
let elapsed_time = start_time.elapsed();
println!(
"[{}μs] {} -- {}",
elapsed_time.as_micros(),
context.request.method(),
context.request.path()
);
Ok(context)
}
#[middleware_fn]
async fn plaintext(mut context: Ctx, _next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
let val = "Hello, World!";
context.body(val);
Ok(context)
}
#[middleware_fn]
async fn four_oh_four(mut context: Ctx, _next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
context.status(404);
context.body("Whoops! That route doesn't exist!");
Ok(context)
}
#[tokio::main]
fn main() {
println!("Starting server...");
let mut app = App::<Request, Ctx, ()>::new_basic();
app.get("/plaintext", m![profile, plaintext]);
app.set404(m![four_oh_four]);
let server = Server::new(app);
server.build("0.0.0.0", 4321).await;
}
错误处理
这里有一个很好的例子
use thruster::errors::ThrusterError as Error;
use thruster::proc::{m, middleware_fn};
use thruster::{map_try, App, BasicContext as Ctx, Request};
use thruster::{MiddlewareNext, MiddlewareResult, MiddlewareReturnValue, Server, ThrusterServer};
#[middleware_fn]
async fn plaintext(mut context: Ctx, _next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
let val = "Hello, World!";
context.body(val);
Ok(context)
}
#[middleware_fn]
async fn error(mut context: Ctx, _next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
let res = "Hello, world".parse::<u32>()
.map_err(|_| {
let mut context = Ctx::default();
context.status(400);
ThrusterError {
context,
message: "Custom error message".to_string(),
cause: None,
}
}?;
context.body(&format!("{}", non_existent_param));
Ok(context)
}
#[tokio::main]
fn main() {
println!("Starting server...");
let app = App::<Request, Ctx, ()>::new_basic()
.get("/plaintext", m![plaintext])
.get("/error", m![error]);
let server = Server::new(app);
server.build("0.0.0.0", 4321).await;
}
测试
Thruster提供了一个简单的测试套件来测试您的端点,只需如下包括testing
模块
let mut app = App::<Request, Ctx, ()>::new_basic();
...
app.get("/plaintext", m![plaintext]);
...
let result = testing::get(app, "/plaintext");
assert!(result.body == "Hello, World!");
创建自己的中间件模块
创建中间件非常简单!只需创建一个函数并在模块级别导出它。下面,您将看到一个允许对请求进行性能分析的中间件示例
#[middleware_fn]
async fn profiling<C: 'static + Context + Send>(
mut context: C,
next: MiddlewareNext<C>,
) -> MiddlewareResult<C> {
let start_time = Instant::now();
context = next(context).await?;
let elapsed_time = start_time.elapsed();
info!("[{}μs] {}", elapsed_time.as_micros(), context.route());
Ok(context)
}
您可能希望能够在上下文中存储更具体的数据,例如,也许您希望能够将查询参数填充到散列表中,供其他中间件稍后使用。为了做到这一点,您可以创建一个额外的trait,中间件必须遵循该trait。查看提供的query_params中间件示例。
其他或自定义后端
Thruster能够仅提供某种服务器之上的路由层,例如,在上面的Hyper片段中。只要服务器实现ThrusterServer
,这就可以广泛应用于任何后端。
use async_trait::async_trait;
#[async_trait]
pub trait ThrusterServer {
type Context: Context + Send;
type Response: Send;
type Request: RequestWithParams + Send;
fn new(App<Self::Request, Self::Context>) -> Self;
async fn build(self, host: &str, port: u16);
}
需要以下内容
- 创建服务器的一种简单方法。
- 一个将服务器构建为异步运行时可以加载的future的函数。
在build
函数中,服务器实现应
- 启动某种类型的监听器以接收连接
- 调用
let matched = app.resolve_from_method_and_path(<某种方法>, <某种路径>);
(这是提供实际路由。) - 调用
app.resolve(<传入请求>, matched)
(这是运行链式中间件。)
为什么你应该使用 Thruster
- 可以随意更改后端。开箱即用,Thruster现在可以通过以下方式使用:actix-web、hyper 或 自定义后端
- Thruster支持从框架级别进行测试
- @trezm 当没有人提交PR或打开问题时,会感到孤独。
- Thruster在更简洁的中间件中心概念上更简洁——例如路由保护。以下是在actix中限制IP的示例
fn ip_guard(head: &RequestHead) -> bool {
// Check for the cloudflare IP header
let ip = if let Some(val) = head.headers().get(CF_IP_HEADER) {
val.to_str().unwrap_or("").to_owned()
} else if let Some(val) = head.peer_addr {
val.to_string()
} else {
return false;
};
"1.2.3.4".contains(&ip)
}
#[actix_web::post("/ping")]
async fn ping() -> Result<HttpResponse, UserPersonalError> {
Ok(HttpResponse::Ok().body("pong"))
}
...
web::scope("/*")
// This is confusing, but we catch all routes that _aren't_
// ip guarded and return an error.
.guard(guard::Not(ip_guard))
.route("/*", web::to(HttpResponse::Forbidden)),
)
.service(ping);
...
这是Thruster
#[middleware_fn]
async fn ip_guard(mut context: Ctx, next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
if "1.2.3.4".contains(&context.headers().get("Auth-Token").unwrap_or("")) {
context = next(context).await?;
Ok(context)
} else {
Err(Error::unauthorized_error(context))
}
}
#[middleware_fn]
async fn ping(mut context: Ctx, _next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
context.body("pong");
Ok(context)
}
...
app.get("/ping", m![ip_guard, plaintext]);
...
更直接一点是件好事!
为什么你不应该使用Thruster
- 维护者很少(基本上只有一个人。)
- 还有其他经过更多实战检验的项目。Thruster正在生产中使用,但无人知晓或关心。
- 它还没有被聪明绝顶的人优化。@trezm 尽力而为,但总是被他的狗(们)分散注意力。
- 说真的,这个框架
可能是确实是很棒,但它肯定没有像其他框架那样被深入研究。您的帮助可以让它更加安全和健壮,但我们可能还没有达到那个阶段。
如果您读到这儿,感谢您的阅读!随时欢迎您联系我们。
依赖项
~53KB