クイックスタート
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トレイトを実装できるようになります。また、関数のパラメータをさまざまな方法で簡潔に記述することができます。
-
元の形式:
#[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トレイトを実装している任意の型を関数の戻り値の型として使用できます。例えば、&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>のようなコマンドで実行できます。