跳转到内容

第一个 REST API

安装了 xidlc 后,我们可以使用它来生成服务端和客户端代码,在这个文章中,我们会:

  1. 定义一个 REST 服务。
  2. 生成 Rust 服务端接口,并创建服务。
  3. 生成 Rust 客户端。并使用客户端访问服务。

创建 hello_world.idl

interface HelloWorld {
@post(path = "/hello")
void say_hello(
in string name
);
};
Terminal window
xidlc gen --output-dir server rust-axum hello_world.idl

现在 xidlc 会在 server 路径下生成服务端代码。

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(())
}
Terminal window
xidlc gen --output-dir client rust-axum --client hello_world.idl

会在当前路径下生成客户端。

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;
}

此外,还可以生成 OpenAPI 文档

Terminal window
xidlc gen openapi hello_world.idl