Crates.io | tonic-build-codec |
lib.rs | tonic-build-codec |
version | 0.6.2 |
source | src |
created_at | 2022-05-07 07:11:02.995098 |
updated_at | 2022-05-09 04:07:00.071718 |
description | Codegen module of `tonic` gRPC implementation. (Add feature to support selecting codec) |
homepage | https://github.com/bysir/tonic |
repository | https://github.com/hyperium/tonic |
max_upload_size | |
id | 582000 |
size | 63,462 |
Compiles proto files via prost and generates service stubs and proto definitiones for use with tonic.
Required dependencies
[dependencies]
tonic = <tonic-version>
prost = <prost-version>
[build-dependencies]
tonic-build = <tonic-version>
In build.rs
:
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::compile_protos("proto/service.proto")?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure()
.disable_package_emission()
.codec("application/grpc | application/grpc+proto", "tonic::codec::ProstCodec")
.codec("application/json | application/grpc+json", "crate::lib::codec::JsonCodec")
.type_attribute(".", "#[derive(serde_derive::Deserialize, serde_derive::Serialize)]")
.compile(&["proto/helloworld.proto", "proto/helpcenter.proto"],&["proto"])?;
Ok(())
}
A good way to use Google API is probably using git submodules.
So suppose in our proto
folder we do:
git submodule add https://github.com/googleapis/googleapis
git submodule update --remote
And a bunch of Google proto files in structure will be like this:
├── googleapis
│ └── google
│ ├── api
│ │ ├── annotations.proto
│ │ ├── client.proto
│ │ ├── field_behavior.proto
│ │ ├── http.proto
│ │ └── resource.proto
│ └── pubsub
│ └── v1
│ ├── pubsub.proto
│ └── schema.proto
Then we can generate Rust code via this setup in our build.rs
fn main() {
tonic_build::configure()
.build_server(false)
//.out_dir("src/google") // you can change the generated code's location
.compile(
&["proto/googleapis/google/pubsub/v1/pubsub.proto"],
&["proto/googleapis"], // specify the root location to search proto dependencies
).unwrap();
}
Then you can reference the generated Rust like this this in your code:
pub mod api {
tonic::include_proto!("google.pubsub.v1");
}
use api::{publisher_client::PublisherClient, ListTopicsRequest};
Or if you want to save the generated code in your own code base,
you can uncomment the line .out_dir(...)
above, and in your lib file
config a mod like this:
pub mod google {
#[path = ""]
pub mod pubsub {
#[path = "google.pubsub.v1.rs"]
pub mod v1;
}
}
See the example here