“google/protobuf/struct.proto”是通过 GRPC 发送动态 JSON 的最佳方式吗?
利用 google.protobuf.Struct 类型提供了一种有效的解决方案用于通过 GRPC 传输动态 JSON 数据。考虑以下 User.proto 文件:
syntax = "proto3"; package messages; import "google/protobuf/struct.proto"; service UserService { rpc SendJson (SendJsonRequest) returns (SendJsonResponse) {} } message SendJsonRequest { string UserID = 1; google.protobuf.Struct Details = 2; } message SendJsonResponse { string Response = 1; }
Anuj 的解决方案:
虽然有效,但这种方法有点复杂:
var item = &structpb.Struct{ Fields: map[string]*structpb.Value{ "name": &structpb.Value{ Kind: &structpb.Value_StringValue{ StringValue: "Anuj", }, }, "age": &structpb.Value{ Kind: &structpb.Value_StringValue{ StringValue: "Anuj", }, }, }, }
卢克的解决方案:
此方法比较简洁,但涉及多次转换:
m := map[string]interface{}{ "foo":"bar", "baz":123, } b, err := json.Marshal(m) s := &structpb.Struct{} err = protojson.Unmarshal(b, s)
推荐方案:
最直接高效方法是利用 structpb 提供的内置函数package:
m := map[string]interface{}{ "name": "Anuj", "age": 23, } details, err := structpb.NewStruct(m) // Check for errors as per documentation if err != nil { panic(err) } userGetRequest := &pb.SendJsonRequest{ UserID: "A123", Details: details, }
请记住遵守 structpb 文档中指定的转换规则,以避免错误。
以上是`google.protobuf.Struct` 是通过 gRPC 发送动态 JSON 的最佳选择吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

goroutinesarefunctionsormethodsthatruncurranceingo,启用效率和灯威量。1)shememanagedbodo'sruntimemultimusingmultiplexing,允许千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

在Go中使用recover()函数可以从panic中恢复。具体方法是:1)在defer函数中使用recover()捕获panic,避免程序崩溃;2)记录详细的错误信息以便调试;3)根据具体情况决定是否恢复程序执行;4)谨慎使用,以免影响性能。

本文讨论了使用GO的“字符串”软件包进行字符串操作,详细介绍了共同的功能和最佳实践,以提高效率并有效地处理Unicode。

本文详细介绍了GO的“时间”包用于处理日期,时间和时区,包括获得当前时间,创建特定时间,解析字符串以及测量经过的时间。


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Dreamweaver CS6
视觉化网页开发工具

记事本++7.3.1
好用且免费的代码编辑器

Atom编辑器mac版下载
最流行的的开源编辑器

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