是"google/protobuf/struct.proto"通过GRPC发送动态JSON的最佳方法? [英] Is "google/protobuf/struct.proto" the best way to send dynamic JSON over GRPC?

查看:422
本文介绍了是"google/protobuf/struct.proto"通过GRPC发送动态JSON的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a written a simple GRPC server and a client to call the server (both in Go). Please tell me if using golang/protobuf/struct is the best way to send a dynamic JSON with GRPC. In the example below, earlier I was creating Details as a map[string]interface{} and serializing it. Then I was sending it in protoMessage as bytes and was de-serializing the message on the server side.

这是最好/最有效的方法吗?还是应该在我的原型文件中将Details定义为结构?

Is it the best/efficient way to do it or should I define Details as a struct in my proto file?

下面是User.proto文件

Below is User.proto file

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文件

Below is client.go file

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

推荐答案

基于此原始文件.

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类型是一个很好的解决方案.

I think it is a good solution to use the google.protobuf.Struct type.

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

The folks with their answers, helped me a lot at the beginning, so I would like to say thanks for your work! :) I really appreciate both solutions! :) On the other hand, I think I found a better one to produce these kinds of Structs.

这有点复杂,但是可以正常工作.

This is a little bit overcomplicated but it can work.

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程序包中的官方功能,该程序包已有很好的文档说明,并且用户友好.

The solution from my perspective

My solution will use the official functions from the structpb package which is pretty well documented and user friendly.

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

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

For example, this code creates a *structpb.Struct via the function that was designed to do this.

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

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

One of the most important thing, that we should keep in mind when we are building Struct from a map[string]interface{} is this:

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.

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

For example, if you would like to produce a Struct that has a string list in its JSON form, you should create the following map[string]interface{}

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

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

Sorry for the long post, I hope it makes your work easier with proto3 and Go! :)

这篇关于是"google/protobuf/struct.proto"通过GRPC发送动态JSON的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆