首頁  >  文章  >  後端開發  >  GO 和 GRPC:「在飛行中」創建 protobuff 類

GO 和 GRPC:「在飛行中」創建 protobuff 類

PHPz
PHPz轉載
2024-02-06 11:06:031230瀏覽

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

以上是GO 和 GRPC:「在飛行中」創建 protobuff 類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除