Rust tonic tonic::include_proto file path from one module to another module in tonic build

2.6k Views Asked by At

I am implementing gRPC client and server using Tonic. I have two modules each module depending on another module proto file. I am facing an issue when I try to provide the path of the proto file in tonic build. Below is my folder structure and code for the tonic build.

   -organization
     -src
       -client
         -mod.rs
       -service
       -cargo.toml
   -Employee
     -src
       -service
       -proto
         -proto_file
       -cargo.toml

pub mod Employee_info {
    tonic::include_proto!("{path}/employee_info.proto"); //this is organisation `mod file`. i want to pass the proto file path of employee folder->proto->proto file.
}
1

There are 1 best solutions below

0
On

You employee_info.proto should be compiled into rust file employee_info.rs.

Your build.rs file should look sth like this:

fn main() {
    let proto_file = "./src/proto/employee_info.proto";
    tonic_build::configure()
        .build_server(true)
        .out_dir("./src")
        .compile(&[proto_file], &["."])
        .unwrap_or_else(|e| panic!("protobuf compile error: {}", e));
    println!("cargo:rerun-if-changed={}", proto_file);
}

After cargo build, expect to see the following file being generated: src/employee_info.rs.

Then you just need include this in your code as usual:

mod employee_info {
    include!("employee_info.rs");
}

As explained in https://docs.rs/tonic/latest/tonic/macro.include_proto.html, you can only include the package via tonic::include_proto when output directory has been unmodified.