Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Twirp RPC for Rust

License

NotificationsYou must be signed in to change notification settings

github/twirp-rs

Twirp is an RPC protocol based on HTTP and Protocol Buffers (proto). The protocol uses HTTP URLs to specify the RPC endpoints, and sends/receives proto messages as HTTP request/response bodies. Services are defined in a.proto file, allowing easy implementation of RPC services with auto-generated clients and servers in different languages.

Thecanonical implementation is in Go, and this is a Rust implementation of the protocol. Rust protocol buffer support is provided by theprost ecosystem.

Unlikeprost-twirp, the generated traits for serving and accessing RPCs are implemented atopasync functions. Because traits containingasync functionsare not directly supported in Rust versions prior to 1.75, this crate uses theasync_trait macro to encapsulate the scaffolding required to make them work.

Usage

See theexample for a complete example project.

Define services and messages in a.proto file:

// service.protopackageservice.haberdash.v1;serviceHaberdasherAPI {rpcMakeHat(MakeHatRequest)returns (MakeHatResponse);}messageMakeHatRequest { }messageMakeHatResponse { }

Add thetwirp-build crate as a build dependency in yourCargo.toml (you'll needprost-build too):

# Cargo.toml[build-dependencies]twirp-build ="0.7"prost-build ="0.13"

Add abuild.rs file to your project to compile the protos and generate Rust code:

fnmain(){let proto_source_files =["./service.proto"];// Tell Cargo to rerun this build script if any of the proto files changefor entryin&proto_source_files{println!("cargo:rerun-if-changed={}", entry);}    prost_build::Config::new().type_attribute(".","#[derive(serde::Serialize, serde::Deserialize)]")// enable support for JSON encoding.service_generator(twirp_build::service_generator()).compile_protos(&proto_source_files,&["./"]).expect("error compiling protos");}

This generates code that you can find intarget/build/your-project-*/out/example.service.rs. In order to use this code, you'll need to implement the trait for the proto defined service and wire up the service handlers to a hyper web server. Seethe example for details.

Include the generated code, create a router, register your service, and then serve those routes in the hyper server:

mod haberdash{include!(concat!(env!("OUT_DIR"),"/service.haberdash.v1.rs"));}use axum::Router;use haberdash::{MakeHatRequest,MakeHatResponse};#[tokio::main]pubasyncfnmain(){let api_impl =Arc::new(HaberdasherApiServer{});let app =Router::new().nest("/twirp", haberdash::router(api_impl)).fallback(twirp::server::not_found_handler);let tcp_listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();ifletErr(e) = axum::serve(tcp_listener, app).await{eprintln!("server error: {}", e);}}// Define the server and implement the trait.structHaberdasherApiServer;#[async_trait]impl haberdash::HaberdasherApiforHaberdasherApiServer{asyncfnmake_hat(&self,req: twirp::Request<MakeHatRequest>) -> twirp::Result<twirp::Response<MakeHatResponse>>{todo!()}}

This code creates anaxum::Router, then hands it off toaxum::serve() to handle networking. This use ofaxum::serve is optional. After buildingapp, you can instead invoke it from anyhyper-based server by importingtwirp::tower::Service and doingapp.call(request).await.

Usage (client side)

On the client side, you also get a generated twirp client (based on the rpc endpoints in your proto). Include the generated code, create a client, and start making rpc calls:

mod haberdash{include!(concat!(env!("OUT_DIR"),"/service.haberdash.v1.rs"));}use haberdash::{HaberdasherApiClient,MakeHatRequest,MakeHatResponse};#[tokio::main]pubasyncfnmain(){let client =Client::from_base_url(Url::parse("http://localhost:3000/twirp/")?)?;let resp = client.make_hat(MakeHatRequest{inches:1}).await;eprintln!("{:?}", resp);}

Minimum supported Rust version

The MSRV for this crate is the version defined inrust-toolchain.toml

Getting Help

You are welcome to open anissue with your question.

Contributing

🎈 Thanks for your help improving the project! We are so happy to have you! We have acontributing guide to help you get involved in the project.

License

This project is licensed under theMIT license.

About

Twirp RPC for Rust

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Contributors16


[8]ページ先頭

©2009-2025 Movatter.jp