我是 GRPC 新手,无法解决一个问题。当应用程序已经运行时是否可以创建 protobuff 文件? 例如,我从用户那里收到这样的
json
:
"protobuf_file": "protobuf.proto", // File will be also recieved from user
"service_name": "Unary",
"method_name": "GetServerResponse",
"request_data_serializer_name": "MessageRequest",
"body": "grpc_request_data.json", // File will be also recieved from user
这里我有一个
.proto
文件、服务名称、方法和消息,以及另一个带有数据的 json 来填充消息。
现在我必须打开连接并使用提供的数据调用所需的方法。
TY!
附注
.proto
文件(来自获取所述指南)将是:
syntax = "proto3";
package protobuf_all_modes;
service Unary {
rpc GetServerResponse(MessageRequest) returns (MessageResponse) {}
}
message MessageRequest {
string message = 1;
}
message MessageResponse {
string message = 1;
int32 random_int32 = 2;
}
第二个
json
将是:
{
"message": "hello World!"
}
我不知道要寻找解决方案。如有任何建议,将不胜感激
是的,为了从任意 json 创建 protobuf 文件,您将需要某种 proto 库。 protojson 是一个很好的选择,但为了使用它,您需要在应用程序中定义 proto 文件。请参阅 https://pkg.go.dev/google.golang.org/protobuf/encoding/protojson 和参数类型 proto.Message。
如果有人遇到同样的问题,有一个非常好的库 - https://pkg.go.dev/github.com/jhump/[email protected]/dynamic 和一个子包 https://pkg。 go.dev/github.com/jhump/[电子邮件受保护]/dynamic/grpcdynamic 代码片段将是:
parser
func NewGrpcObject(operation *BaseOperation) *GrpcObject {
fns, err := protoparse.ResolveFilenames([]string{"./"}, operation.ProtoFile) // prase .proto file
if err != nil {
log.Error(err)
}
parser := protoparse.Parser{}
fds, err := parser.ParseFiles(fns...)
if err != nil {
log.Error(err)
}
descriptor := fds[0] // In my case there will be only one .proto
pkg := descriptor.GetPackage()
serviceDescriptor := descriptor.FindService(pkg + "." + operation.ServiceName) // name of service descriptor will be with package name first
methodDescriptor := serviceDescriptor.FindMethodByName(operation.MethodName) // name of method descriptor will be with package name first
requestDescriptor := methodDescriptor.GetInputType() // You can get types for request and response
responseDescriptor := methodDescriptor.GetOutputType()
return &GrpcObject{
RequestDesc: requestDescriptor,
MethodDesc: methodDescriptor,
ResponseDesc: responseDescriptor,
}
}
caller
// connect
conn, _ := grpc.Dial(operation.Host, grpc.WithTransportCredentials(credentials.NewTLS(c.TLSClientConfig.NewTLSConfig())))
stub = grpcdynamic.NewStub(conn)
// call
message := dynamic.NewMessage(operation.GrpcObject.RequestDesc) // from parser
message.UnmarshalJSON(operation.Body) // here a JSON to fill message
resp, err := stub.InvokeRpc(ctx, operation.GrpcObject.MethodDesc, message)
if err != nil {
// handle err
}
respMessage := dynamic.NewMessage(operation.GrpcObject.ResponseDesc) // descriptor from parser
respMessage.ConvertFrom(resp) // convert message from raw response