快速开始
安装 Rust
如果你还没有安装 Rust, 你可以使用官方提供的 (rustup)[https://doc.rust-lang.org/book/ch01-01-installation.html] 安装 Rust.
Tip
当前 Salvo 支持的最低 Rust 版本为 1.89. 运行 rustup update 确认您已经安装了符合要求的 Rust.
编写第一个 Salvo 程序
创建一个全新的项目:
添加依赖项到 Cargo.toml
[package]
name = "example-hello"
version.workspace = true
edition.workspace = true
publish.workspace = true
rust-version.workspace = true
[dependencies]
salvo = { workspace = true }
tokio = { workspace = true, features = ["macros"] }
tracing.workspace = true
tracing-subscriber.workspace = true
在 main.rs 中创建一个简单的函数句柄, 命名为 hello, 这个函数只是简单地打印文本 "Hello world".
use salvo::prelude::*;
// Handler for English greeting
#[handler]
async fn hello() -> &'static str {
"Hello World"
}
// Handler for Chinese greeting
#[handler]
async fn hello_zh() -> Result<&'static str, ()> {
Ok("你好,世界!")
}
#[tokio::main]
async fn main() {
// Initialize logging subsystem
tracing_subscriber::fmt().init();
// Bind server to port 8698
let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
// Create router with two endpoints:
// - / (root path) returns English greeting
// - /你好 returns Chinese greeting
let router = Router::new()
.get(hello)
.push(Router::with_path("你好").get(hello_zh));
// Print router structure for debugging
println!("{router:?}");
// Start serving requests
Server::new(acceptor).serve(router).await;
}
恭喜你, 你的一个 Salvo 程序已经完成. 只需要在命令行下运行 cargo run, 然后在浏览器里打开 http://127.0.0.1:8698 即可.
详细解读
这里的 hello_world 是一个 Handler, 用于处理用户请求. #[handler] 可以让一个函数方便实现 Handler trait. 并且, 它允许我们用不同的方式简写函数的参数.
-
原始形式:
#[handler]
async fn hello(_req: &mut Request, _depot: &mut Depot, res: &mut Response, _ctrl: &mut FlowCtrl) {
res.render("Hello world");
}
-
您可以省略函数中某些用不着的参数, 比如这里面的 _req, _depot, _ctrl 都没有被使用, 可以直接不写:
#[handler]
async fn hello(res: &mut Response) {
res.render("Hello world");
}
-
任何类型都可以作为函数的返回类型, 只要它实现了 Writer trait. 比如 &str 实现了 Writer, 当它被作为返回值时, 就打印纯文本:
#[handler]
async fn hello(res: &mut Response) -> &'static str {
"Hello world"
}
-
更普遍的情况是, 我们需要在将 Result<T, E> 作为返回类型, 以便处理函数执行过程中的错误. 如果 T 和 E 都实现了 Writer, 那么 Result<T, E> 就可以作为返回值:
#[handler]
async fn hello(res: &mut Response) -> Result<&'static str, ()> {
Ok("Hello world")
}
风骚的 HTTP3
据说 HTTP3 身轻如燕,多少程序员思而不得,这回,Salvo 就帮大家实现愿望,让大家轻松享受到 HTTP3 带来的美妙服务!
首先在 Cargo.toml 中启用 HTTP3 功能, 然后把 main.rs 改成这样:
use salvo::conn::rustls::{Keycert, RustlsConfig};
use salvo::prelude::*;
// Handler function responding with "Hello World" for HTTP/3 requests
#[handler]
async fn hello() -> &'static str {
"Hello World"
}
#[tokio::main]
async fn main() {
// Initialize logging system
tracing_subscriber::fmt().init();
// Load TLS certificate and private key from embedded PEM files
let cert = include_bytes!("../certs/cert.pem").to_vec();
let key = include_bytes!("../certs/key.pem").to_vec();
// Create router with single endpoint
let router = Router::new().get(hello);
// Configure TLS settings using Rustls
let config = RustlsConfig::new(Keycert::new().cert(cert.as_slice()).key(key.as_slice()));
// Create TCP listener with TLS encryption on port 8698
let listener = TcpListener::new(("0.0.0.0", 8698)).rustls(config.clone());
// Create QUIC listener and combine with TCP listener
let acceptor = QuinnListener::new(config.build_quinn_config().unwrap(), ("0.0.0.0", 8698))
.join(listener)
.bind()
.await;
// Start server supporting both HTTP/3 (QUIC) and HTTPS (TCP)
Server::new(acceptor).serve(router).await;
}
[package]
name = "example-hello-h3"
version.workspace = true
edition.workspace = true
publish.workspace = true
rust-version.workspace = true
[dependencies]
salvo = { workspace = true, features = ["quinn"] }
tokio = { workspace = true, features = ["macros"] }
tracing.workspace = true
tracing-subscriber.workspace = true
Salvo CLI 工具 🛠️
Salvo CLI 是为 Salvo web 框架设计的工具,它能够创建整洁、易读的代码,节省您的时间用于生活中更有趣的事情。
如果您有改进 CLI 的想法,或者发现了一些需要解决的问题,请不要犹豫!提交一个 issue,我们欢迎您的见解。
第 1 步
安装CLI工具:
第 2 步
创建一个新的 Salvo 项目,使用 new 命令后面跟上您的项目名称:
您可以通过这个简单的 CLI 工具快速启动 Salvo 项目,专注于实现您的业务逻辑,而不是项目结构搭建。 ✨
更多示例
建议直接克隆 Salvo 仓库, 然后运行 examples 目录下的示例. 比如下面的命令可以运行 hello 的例子:
git clone https://github.com/salvo-rs/salvo
cd salvo/examples
cargo run --bin example-hello
examples 目录下有很多的例子. 都可以通过类似 cargo run --bin example-<name> 的命令运行.