如何将数据传递给toniconeof
中的 protobuf ?
我在文档中找不到任何说明或示例。
Tonic 应该enum
为每个oneof
变体生成一个对应的类型。您必须对此进行匹配。
对于这个答案,我假设tonic = "0.4.3"
和或更高。prost = "0.7.0"
让我们以以下.proto
定义为例:
syntax = "proto3";
package stack_overflow;
service StackOverflow {
rpc Question (HelpRequest) returns (HelpResponse);
}
message HelpRequest {
oneof foo {
FroozleType froozle = 1;
FrobnikType frobnik = 2;
}
}
message FroozleType {
int32 value = 1;
}
message FrobnikType {}
message HelpResponse {
oneof bar {
QuxType qux = 1;
BazType baz = 2;
}
}
message QuxType {
int32 answer = 1;
}
message BazType {
string comment = 1;
}
构建后,这会生成以下类型和特征。对于服务:
stack_overflow_server::StackOverflow
: 服务器特性对于请求:
HelpRequest
: 请求消息的结构help_request::Foo
: 请求中的枚举,oneof foo
具有一个Froozle
和一个Frobnik
变体FroozleType
:FroozleType
消息的结构FrobnikType
:FrobnikType
消息的结构对于回复:
HelpResponse
: 响应消息的结构help_response::Bar
oneof bar
:响应中的枚举,具有一个Qux
和一个Baz
变体QuxType
:QuxType
消息的结构BazType
:BazType
消息的结构例如,HelpRequest
struct 和help_request::Foo
enum 定义如下:
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HelpRequest {
#[prost(oneof = "help_request::Foo", tags = "1, 2")]
pub foo: ::core::option::Option<help_request::Foo>,
}
/// Nested message and enum types in `HelpRequest`.
pub mod help_request {
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Foo {
#[prost(message, tag = "1")]
Froozle(super::FroozleType),
#[prost(message, tag = "2")]
Frobnik(super::FrobnikType),
}
}
将它们放在一起,上述服务的示例实现可能如下所示:
use tonic::{Request, Response, Status};
mod grpc {
tonic::include_proto!("stack_overflow");
}
#[derive(Debug)]
pub struct StackOverflowService {}
#[tonic::async_trait]
impl grpc::stack_overflow_server::StackOverflow for StackOverflowService {
async fn question(
&self,
request: Request<grpc::HelpRequest>,
) -> Result<Response<grpc::HelpResponse>, Status> {
let request = request.into_inner();
let bar = match request.foo {
Some(grpc::help_request::Foo::Froozle(froozle)) => {
Some(grpc::help_response::Bar::Qux(grpc::QuxType {
answer: froozle.value + 42,
}))
}
Some(grpc::help_request::Foo::Frobnik(_)) => {
Some(grpc::help_response::Bar::Baz(grpc::BazType {
comment: "forty-two".into(),
}))
}
None => None,
};
let reply = grpc::HelpResponse { bar };
return Ok(Response::new(reply));
}
}