登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-13 09:45:31 405浏览 收藏

golang学习网今天将给大家带来《“google/protobuf/struct.proto”是通过 GRPC 发送动态 JSON 的最佳方式吗?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

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

这是最好/有效的方法还是我应该将详细信息定义为我的原型文件中的结构?

下面是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)
}

解决方案


基于此原型文件。

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[字符串]接口{} -> 字节 -> 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,
}

当我们从 map[string]interface{} 构建 struct 时,我们应该记住的最重要的事情之一是:

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] 接口{}

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

很抱歉这篇文章很长,我希望它能让您使用 proto3go 的工作更轻松! :)

以上就是《“google/protobuf/struct.proto”是通过 GRPC 发送动态 JSON 的最佳方式吗?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>