卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34254本站已运行391

GO 和 GRPC:“在飞行中”创建 protobuff 类

go 和 grpc:“在飞行中”创建 protobuff 类

问题内容

我是 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!"
}

我不知道要寻找解决方案。如有任何建议,将不胜感激


正确答案


如果有人遇到同样的问题,有一个非常好的库 - 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)
    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
卓越飞翔博客
上一篇: 将文本文件放入切片然后比较
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏