我是 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中文网其他相关文章!

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

开发者应遵循以下最佳实践:1.谨慎管理goroutines以防止资源泄漏;2.使用通道进行同步,但避免过度使用;3.在并发程序中显式处理错误;4.了解GOMAXPROCS以优化性能。这些实践对于高效和稳健的软件开发至关重要,因为它们确保了资源的有效管理、同步的正确实现、错误的适当处理以及性能的优化,从而提升软件的效率和可维护性。

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

我们需要自定义错误类型,因为标准错误接口提供的信息有限,自定义类型能添加更多上下文和结构化信息。1)自定义错误类型能包含错误代码、位置、上下文数据等,2)提高调试效率和用户体验,3)但需注意其复杂性和维护成本。

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3汉化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript开发工具