将 ptypes/struct 值转换为 BSON

Go converting ptypes/struct Value to BSON

要求

两项服务:

博客 post 有 title 类型 stringcontent 是动态类型 - 可以是任何 JSON 值。

Protobuf

syntax = "proto3";

package blog;

option go_package = "blogpb";

import "google/protobuf/struct.proto";

message Blog {
  string id = 1;
  string title = 2;
  google.protobuf.Value content = 3;
}

message CreateBlogRequest {
  Blog blog = 1;
}

message CreateBlogResponse {
  Blog blog = 1;
}

service BlogService {
  rpc CreateBlog (CreateBlogRequest) returns (CreateBlogResponse);
}

让我们从 protobuf 消息开始,它符合要求 - string 用于 title 和任何 JSON 值用于 content

客户

package main

import (...)

func main() {
    cc, _ := grpc.Dial("localhost:50051", grpc.WithInsecure())
    defer cc.Close()
    c := blogpb.NewBlogServiceClient(cc)

    var blog blogpb.Blog

    json.Unmarshal([]byte(`{"title": "First example", "content": "string"}`), &blog)
    c.CreateBlog(context.Background(), &blogpb.CreateBlogRequest{Blog: &blog})

    json.Unmarshal([]byte(`{"title": "Second example", "content": {"foo": "bar"}}`), &blog)
    c.CreateBlog(context.Background(), &blogpb.CreateBlogRequest{Blog: &blog})
}

客户端向服务器发送两个请求 - 一个 content 具有 string 类型,另一个具有 object 类型。这里没有错误。

服务器

package main

import (...)

var collection *mongo.Collection

type server struct {
}

type blogItem struct {
    ID      primitive.ObjectID `bson:"_id,omitempty"`
    Title   string             `bson:"title"`
    Content *_struct.Value     `bson:"content"`
}

func (*server) CreateBlog(ctx context.Context, req *blogpb.CreateBlogRequest) (*blogpb.CreateBlogResponse, error) {
    blog := req.GetBlog()

    data := blogItem{
        Title:   blog.GetTitle(),
        Content: blog.GetContent(),
    }

    // TODO: convert "data" or "data.Content" to something that could be BSON encoded..

    res, err := collection.InsertOne(context.Background(), data)
    if err != nil {
        log.Fatal(err)
    }
    oid, _ := res.InsertedID.(primitive.ObjectID)

    return &blogpb.CreateBlogResponse{
        Blog: &blogpb.Blog{
            Id:      oid.Hex(),
            Title:   blog.GetTitle(),
            Content: blog.GetContent(),
        },
    }, nil

}

func main() {
    client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    client.Connect(context.TODO())
    collection = client.Database("mydb").Collection("blog")
    lis, _ := net.Listen("tcp", "0.0.0.0:50051")
    s := grpc.NewServer([]grpc.ServerOption{}...)
    blogpb.RegisterBlogServiceServer(s, &server{})
    reflection.Register(s)
    go func() { s.Serve(lis) }()
    ch := make(chan os.Signal, 1)
    signal.Notify(ch, os.Interrupt)
    <-ch
    client.Disconnect(context.TODO())
    lis.Close()
    s.Stop()
}

我得到:

cannot transform type main.blogItem to a BSON Document: no encoder found for structpb.isValue_Kind

我期待什么?要查看 MongoDB 中内容的确切值,如下所示:

{ "_id" : ObjectId("5e5f6f75d2679d058eb9ef79"), "title" : "Second example", "content": "string" }
{ "_id" : ObjectId("5e5f6f75d2679d058eb9ef78"), "title" : "First example", "content": { "foo": "bar" } }

我想我需要在我添加 TODO:...

的行中转换 data.Content

如果有帮助,我可以用这个例子创建 github 存储库。

因此,正如@nguyenhoai890 在评论中所建议的那样,我设法使用 jsonpb lib 修复它 - 首先 MarshalToStringstructpb 转换为 string(json),然后 json.Unmarshalstring(json) 转换为 BSON 支持的 interface{}。此外,我还必须修复客户端以正确地将字符串解组为 protobuf。

客户

func main() {
    cc, _ := grpc.Dial("localhost:50051", grpc.WithInsecure())
    defer cc.Close()
    c := blogpb.NewBlogServiceClient(cc)

    var blog blogpb.Blog
    jsonpb.UnmarshalString(`{"title": "Second example", "content": {"foo": "bar"}}`, &blog)
    c.CreateBlog(context.Background(), &blogpb.CreateBlogRequest{Blog: &blog})

    jsonpb.UnmarshalString(`{"title": "Second example", "content": "stirngas"}`, &blog)
    c.CreateBlog(context.Background(), &blogpb.CreateBlogRequest{Blog: &blog})
}

服务器

type blogItem struct {
    ID      primitive.ObjectID `bson:"_id,omitempty"`
    Title   string             `bson:"title"`
    Content interface{}        `bson:"content"`
}

func (*server) CreateBlog(ctx context.Context, req *blogpb.CreateBlogRequest) (*blogpb.CreateBlogResponse, error) {
    blog := req.GetBlog()

    contentString, err := new(jsonpb.Marshaler).MarshalToString(blog.GetContent())
    if err != nil {
        log.Fatal(err)
    }

    var contentInterface interface{}
    json.Unmarshal([]byte(contentString), &contentInterface)

    data := blogItem{
        Title:   blog.GetTitle(),
        Content: contentInterface,
    }

    res, err := collection.InsertOne(context.Background(), data)
    if err != nil {
        log.Fatal(err)
    }
    oid, _ := res.InsertedID.(primitive.ObjectID)

    return &blogpb.CreateBlogResponse{
        Blog: &blogpb.Blog{
            Id:      oid.Hex(),
            Title:   blog.GetTitle(),
            Content: blog.GetContent(),
        },
    }, nil

}