第一个 REST API
安装了 xidlc 后,我们可以使用它来生成服务端和客户端代码,在这个文章中,我们会:
- 定义一个 REST 服务。
- 生成 Rust 服务端接口,并创建服务。
- 生成 Rust 客户端。并使用客户端访问服务。
1. 定义一个 REST 接口
Section titled “1. 定义一个 REST 接口”创建 hello_world.idl:
interface HelloWorld { @post(path = "/hello") void say_hello( in string name );};2. 生成 Rust 服务端代码
Section titled “2. 生成 Rust 服务端代码”xidlc gen --output-dir server rust-axum hello_world.idl现在 xidlc 会在 server 路径下生成服务端代码。
3. 创建服务端
Section titled “3. 创建服务端”include!("./server/hello_world.rs");
struct HelloWorldImpl;
#[async_trait::async_trait]impl HelloWorld for HelloWorldImpl { async fn sayHello(&self, name: String) -> Result<(), xidl_rust_axum::Error> { println!("Hello, {}!", name); Ok(()) }}
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let addr = "127.0.0.1:3000"; println!("axum hello_world server listening on {addr}");
xidl_rust_axum::Server::builder() .with_service(HelloWorldServer::new(HelloWorldImpl)) .serve(addr) .await?;
Ok(())}4. 生成客户端接口
Section titled “4. 生成客户端接口”xidlc gen --output-dir client rust-axum --client hello_world.idl会在当前路径下生成客户端。
5. 使用客户端
Section titled “5. 使用客户端”include!("./client/hello_world.rs");
#[tokio::main]async fn main() { let client = HelloWorldClient::new("http://127.0.0.1:8080"); let _ = client.say_hello("world".to_string()).await;}6. 生成 OpenAPI 文档
Section titled “6. 生成 OpenAPI 文档”此外,还可以生成 OpenAPI 文档
xidlc gen openapi hello_world.idl