gRPC 方法 return 可以包含一个字段可以是字符串或空的消息吗?

Can gRPC method return a message with a field that could be string or null?

我正在设计一个用 Go 编写的 gRPC 服务。

在 gRPC 服务前面是 Envoy,它将传入的 HTTP 请求转换为 gRPC,并将 gRPC 响应转换为 JSON。

此应用程序的要求是有一个端点 returns 以下 JSON 对象:

{
    my_id: "AAA"
}

我可以像这样在 Go 中非常简单地模拟此响应:

// A MyResponse object.
message MyResponse {
  // contents is a list of contents.
  string my_id = 1;
}

但我的要求是有时 my_id 可能为空。在这种情况下,我想得到以下 JSON 返回:

{
    my_id: null
}

是否可以修改 MyResponse,使返回的 JSON 对象中的 my_id 可以是字符串或空值?如果是这样,如何?如果不是,这不是gRPC设计上的一个很大的差距吗?

我建议您使用包的 StringValue 字段 google.protobuf:

StringValue Wrapper message for string.

The JSON representation for StringValue is JSON string.

所以在你的原型文件中,你应该导入:

import "google/protobuf/wrappers.proto";

然后作为示例:

  google.protobuf.StringValue name = 2;

对于处理值,您可以检查 wrappers.StringValue github.com/golang/protobuf/ptypes/wrappers package and the helpers of the google.golang.org/protobuf/types/known/wrapperspb 仓库的类型。