业务场景
- 加载项目配置
- 编写带命令和参数的程序
- 编写 http server
常用库
prost-build
描述:
prost-build
是一个用于生成 Protobuf 文件的 Rust 构建工具。用途:
它用于从.proto
文件生成 Rust 代码,帮助开发者在 Rust 项目中使用 Protocol Buffers。学习资源:
常用api:
1
2
3
4
5
6
7
8
9
10println!("cargo:rerun-if-changed=proto/event.proto");
prost_build::Config::new()
.protoc_arg("--experimental_allow_proto3_optional")
.btree_map(["."])
.bytes(["raw_bytes"])
.compile_protos(
&["proto/event.proto"],
&["proto", "../../proto/third-party", "../../proto/vector"],
)
.unwrap();
reqwest
描述:
reqwest
是一个用于发送 HTTP 请求的 Rust 库,支持同步和异步 API。用途:
reqwest
用于在 Rust 程序中进行 HTTP 请求操作,如发送 GET 和 POST 请求、处理 JSON 数据等。它非常适合用来与 RESTful API 进行交互。学习资源:
常用api:
1
2
3
4
5
6
7
8
9
10
11
12// 异步 GET 请求
use reqwest;
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let response = reqwest::get("https://api.github.com/repos/rust-lang/rust")
.await?
.text()
.await?;
println!("Response: {}", response);
Ok(())
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// 异步 POST 请求,发送 JSON 数据
use reqwest::Client;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let client = Client::new();
let response = client.post("https://httpbin.org/post")
.json(&json!({ "name": "Rust", "type": "language" }))
.send()
.await?
.text()
.await?;
println!("Response: {}", response);
Ok(())
}1
2
3
4
5
6
7
8
9// 同步 GET 请求
use reqwest::blocking;
fn main() -> Result<(), reqwest::Error> {
let response = blocking::get("https://api.github.com/repos/rust-lang/rust")?
.text()?;
println!("Response: {}", response);
Ok(())
}
config
描述:
config
是一个强大的 Rust 配置管理库,支持从多个来源加载和合并配置,如文件、环境变量、命令行参数等。用途:
config
库用于管理应用程序的配置数据,可以从多种来源读取配置并进行合并和覆盖,支持层级结构和类型安全的配置访问。学习资源:
常用api:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32use config::{Config, File, Environment, FileFormat};
#[derive(Debug, Deserialize)]
struct Settings {
debug: bool,
version: String,
database: DatabaseSettings,
}
#[derive(Debug, Deserialize)]
struct DatabaseSettings {
url: String,
pool_size: u32,
}
fn main() -> Result<(), config::ConfigError> {
// 创建 Config 对象
let mut settings = Config::default();
// 从文件加载配置
settings.merge(File::new("config/default", FileFormat::Toml))?;
// 从环境变量加载配置
settings.merge(Environment::with_prefix("APP"))?;
// 解析配置到结构体
let settings: Settings = settings.try_into()?;
println!("Settings: {:?}", settings);
Ok(())
}
解释
创建 Config 对象:
1
let mut settings = Config::default();
初始化一个默认的
Config
对象。从文件加载配置:
1
settings.merge(File::new("config/default", FileFormat::Toml))?;
从指定路径的文件加载配置,这里假设文件格式为 TOML。
从环境变量加载配置:
1
settings.merge(Environment::with_prefix("APP"))?;
从环境变量加载配置,并使用指定的前缀(如
APP_DEBUG
对应debug
配置项)。解析配置到结构体:
1
let settings: Settings = settings.try_into()?;
将加载的配置解析到预定义的结构体中,方便类型安全的访问。
Rocket
描述:
Rocket
是一个用于构建 Web 应用程序的易于使用且灵活的 Rust Web 框架。它提供了类型安全的路由和请求处理,使得开发 Web 服务变得非常简单。用途:
Rocket
库用于快速构建高效、可靠的 Web 应用程序和 API。它支持路由、请求和响应处理、参数解析、表单处理等功能,并且具有良好的类型安全性。学习资源:
常用api:
1
2
3
4
5
6
7
8
9
10
11
12
13
14#[macro_use] extern crate rocket;
// 定义一个简单的 GET 路由处理函数
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
// 启动 Rocket 服务器
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index])
}
解释
引入 Rocket 宏:
1
#[macro_use] extern crate rocket;
这行代码引入了 Rocket 宏,使得你可以使用路由宏(如
#[get]
)来定义请求处理函数。定义路由处理函数:
1
2
3
4#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}使用
#[get("/")]
宏定义一个处理 GET 请求的路由函数index
,该函数返回一个静态字符串。启动 Rocket 服务器:
1
2
3
4
5#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index])
}使用
#[launch]
宏标记rocket
函数,该函数构建并启动 Rocket 服务器。mount
方法将定义的路由挂载到根路径/
。
使用示例
假设你有一个更复杂的应用程序,需要处理多个路由和参数:
1 |
|
解释
定义带参数的路由:
1
2
3
4#[get("/hello/<name>")]
fn hello(name: &str) -> String {
format!("Hello, {}!", name)
}这个路由处理函数
hello
接受一个路径参数name
,并返回一个包含该参数的字符串。定义 POST 路由处理函数:
1
2
3
4#[post("/submit", data = "<input>")]
fn submit(input: String) -> String {
format!("You submitted: {}", input)
}这个路由处理函数
submit
处理 POST 请求,并接受请求体数据input
,然后返回一个包含该数据的字符串。启动 Rocket 服务器:
1
2
3
4
5#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![hello, submit])
}启动 Rocket 服务器,并将定义的路由挂载到根路径
/
。
通过 Rocket
,你可以快速构建和部署 Web 应用程序,享受其简洁且类型安全的 API。