跳到主要内容

Rust

首先阅读 gRPC 指南,获取平台 API 令牌并下载 platform.proto。本示例使用 tonic 和 tonic-prost-build 生成原生 HTTP/2 客户端。请先安装 Rust 和 protoc。

创建项目,并将下载的契约放在 proto/platform.proto:

cargo new reconstruct-client
cd reconstruct-client
mkdir proto

使用以下 Cargo.toml:

[package]
name = "reconstruct-client"
version = "0.1.0"
edition = "2021"

[dependencies]
prost = "0.14"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tonic = { version = "0.14", features = ["transport", "tls-ring", "tls-native-roots"] }
tonic-prost = "0.14"

[build-dependencies]
tonic-prost-build = "0.14"

在项目根目录使用 build.rs,在构建期间生成客户端类型:

fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_prost_build::configure()
.build_server(false)
.compile_protos(&["proto/platform.proto"], &["proto"])?;
Ok(())
}

在 src/main.rs 中使用生成的客户端:

use std::env;
use tonic::{transport::{Channel, ClientTlsConfig}, Request};

pub mod platform {
tonic::include_proto!("reconstruct.platform.v1");
}

use platform::{
platform_service_client::PlatformServiceClient,
GetCatalogRequest, ListCatalogsRequest,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let token = env::var("CR_RECONSTRUCT_API_TOKEN")?;
let channel = Channel::from_static("https://reconstruct.dev")
.tls_config(ClientTlsConfig::new().with_native_roots())?
.connect()
.await?;
let mut client = PlatformServiceClient::new(channel);

let mut request = Request::new(ListCatalogsRequest {
page_size: 10,
page_token: String::new(),
});
request.metadata_mut().insert("authorization", format!("Bearer {token}").parse()?);
let page = client.list_catalogs(request).await?.into_inner();

for catalog in page.catalogs {
let mut request = Request::new(GetCatalogRequest { catalog_id: catalog.catalog_id });
request.metadata_mut().insert("authorization", format!("Bearer {token}").parse()?);
let detail = client.get_catalog(request).await?.into_inner();
println!("{}: {}", detail.catalog_id, detail.description);
}
Ok(())
}

运行 cargo run。原生 gRPC 连接到 HTTPS 主机和端口;/api/v1/platform 仅适用于 REST。