34 releases

0.11.0 Feb 8, 2024
0.10.2 Sep 28, 2023
0.9.2 Apr 17, 2023
0.9.0 Mar 31, 2023
0.1.0-alpha.6 Nov 10, 2019

#54 in Network programming

Download history 504781/week @ 2023-12-08 478918/week @ 2023-12-15 193819/week @ 2023-12-22 312535/week @ 2023-12-29 495610/week @ 2024-01-05 493497/week @ 2024-01-12 527774/week @ 2024-01-19 474120/week @ 2024-01-26 494260/week @ 2024-02-02 534374/week @ 2024-02-09 485627/week @ 2024-02-16 600536/week @ 2024-02-23 596598/week @ 2024-03-01 525695/week @ 2024-03-08 561322/week @ 2024-03-15 450767/week @ 2024-03-22

2,247,295 downloads per month
Used in 859 crates (431 directly)

MIT license

93KB
2K SLoC

tonic-build

Compiles proto files via prost and generates service stubs and proto definitions for use with tonic.

Features

Required dependencies

[dependencies]
tonic = <tonic-version>
prost = <prost-version>

[build-dependencies]
tonic-build = <tonic-version>

Examples

Simple

In build.rs:

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tonic_build::compile_protos("proto/service.proto")?;
    Ok(())
}

Configuration

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

See more examples here

Google APIs example

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

Dependencies

~0.5–12MB
~126K SLoC