【发布时间】:2019-03-28 17:14:32
【问题描述】:
我编写了一个简单的 GRPC 服务器和一个调用服务器的客户端(都在 Go 中)。请告诉我使用 golang/protobuf/struct 是否是使用 GRPC 发送动态 JSON 的最佳方式。
在下面的示例中,之前我将Details 创建为map[string]interface{} 并对其进行序列化。然后我在 protoMessage 中以bytes 发送它,并在服务器端反序列化消息。
这是最好/最有效的方法,还是我应该在我的原型文件中将 Details 定义为结构?
下面是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;
}
下面是client.go文件
package main
import (
"context"
"flag"
pb "grpc-test/messages/pb"
"log"
"google.golang.org/grpc"
)
func main() {
var serverAddr = flag.String("server_addr", "localhost:5001", "The server address in the format of host:port")
opts := []grpc.DialOption{grpc.WithInsecure()}
conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
log.Fatalf("did not connect: %s", err)
}
defer conn.Close()
userClient := pb.NewUserServiceClient(conn)
ctx := context.Background()
sendJson(userClient, ctx)
}
func sendJson(userClient pb.UserServiceClient, ctx context.Context) {
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",
},
},
},
}
userGetRequest := &pb.SendJsonRequest{
UserID: "A123",
Details: item,
}
res, err := userClient.SendJson(ctx, userGetRequest)
}
【问题讨论】:
标签: json go protocol-buffers grpc protoc