“ google / protobuf / struct.proto”是通过GRPC发送动态JSON的最佳方法吗?

时间:2018-10-24 10:16:33

标签: json go protocol-buffers grpc protoc

我编写了一个简单的GRPC服务器和一个客户端来调用服务器(都在Go中)。请告诉我是否使用golang / protobuf / struct是使用GRPC发送动态JSON的最佳方法。 在下面的示例中,我之前是将Details创建为map [string] interface {}并将其序列化。然后,我在protoMessage中将其作为字节发送,并在服务器端反序列化该消息。

这是最好/最有效的方法吗?还是应该在Proto文件中将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文件     包主     导入(         “上下文”         “旗”         pb“ grpc-test / messages / pb”         “日志”

    "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)
}

3 个答案:

答案 0 :(得分:3)

我最终使用了protojson的两步转换,从映射到json到结构:

m := map[string]interface{}{
  "foo":"bar",
  "baz":123,
}
b, err := json.Marshal(m)
s := &structpb.Struct{}
err = protojson.Unmarshal(b, s)

我觉得它并不优雅,但实际上找不到关于如何进行此操作的任何官方文档。我也更喜欢使用“官方”功能生成结构,而不是尝试自己构建结构。

答案 1 :(得分:1)

如果已经有JSON数据,则还可以选择将其编码为字符串字段。否则,使用google.protobuf.Struct似乎很合理,并且您应该能够使用jsonpb在客户端和服务器上轻松地在Struct和JSON之间进行转换。

答案 2 :(得分:1)

基于此原始文件。

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;
}

我认为使用google.protobuf.Struct类型是一个很好的解决方案。

乡亲们的回答一开始对我有很大帮助,所以我要感谢您的工作! :)我真的很感谢这两种解决方案! :) 另一方面,我认为我找到了一种更好的方法来生产这类Structs

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",
            },
        },
    },
}

卢克的解决方案

这是一个较短的代码,但仍需要更多的转换。 map[string]interface{} -> bytes -> Struct

m := map[string]interface{}{
  "foo":"bar",
  "baz":123,
}
b, err := json.Marshal(m)
s := &structpb.Struct{}
err = protojson.Unmarshal(b, s)

从我的角度来看的解决方案

我的解决方案将使用structpb软件包中的正式功能,该文件已被很好地记录且易于使用。

文档: https://pkg.go.dev/google.golang.org/protobuf/types/known/structpb

例如,这段代码通过旨在执行此操作的函数创建了*structpb.Struct

m := map[string]interface{}{
    "name": "Anuj",
    "age":  23,
}

details, err := structpb.NewStruct(m) // Check to rules below to avoid errors
if err != nil {
    panic(err)
}

userGetRequest := &pb.SendJsonRequest{
    UserID: "A123",
    Details: details,
}

Struct构建map[string]interface{}时应牢记的最重要的事情之一是:

https://pkg.go.dev/google.golang.org/protobuf/types/known/structpb#NewValue

// NewValue constructs a Value from a general-purpose Go interface.
//
//  ╔════════════════════════╤════════════════════════════════════════════╗
//  ║ Go type                │ Conversion                                 ║
//  ╠════════════════════════╪════════════════════════════════════════════╣
//  ║ nil                    │ stored as NullValue                        ║
//  ║ bool                   │ stored as BoolValue                        ║
//  ║ int, int32, int64      │ stored as NumberValue                      ║
//  ║ uint, uint32, uint64   │ stored as NumberValue                      ║
//  ║ float32, float64       │ stored as NumberValue                      ║
//  ║ string                 │ stored as StringValue; must be valid UTF-8 ║
//  ║ []byte                 │ stored as StringValue; base64-encoded      ║
//  ║ map[string]interface{} │ stored as StructValue                      ║
//  ║ []interface{}          │ stored as ListValue                        ║
//  ╚════════════════════════╧════════════════════════════════════════════╝
//
// When converting an int64 or uint64 to a NumberValue, numeric precision loss
// is possible since they are stored as a float64.

例如,如果您要生成一个Struct且具有JSON格式的字符串列表,则应创建以下map[string]interface{}

m := map[string]interface{}{
    "name": "Anuj",
    "age":  23,
    "cars": []interface{}{
        "Toyota",
        "Honda",
        "Dodge",
    }
}

很抱歉,很长的帖子,希望通过proto3Go使您的工作更轻松! :)