Skip to content

codec of the Well Known google.protobuf.Struct type which generated by gogo protobuf

Notifications You must be signed in to change notification settings

rueian/gogo-struct-codec

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

gogo-struct-codec

codec of the Well Known google.protobuf.Struct type which generated by gogo protobuf

Drop-in replacement for gogo's types.Struct

The ptypes.Struct is provided as a drop-in replacement for the gogo's types.Struct which doesn't be implemented with common Marshal/Unmarshal interfaces.

Currently ptypes.Struct is implemented by embedding gogo's types.Struct and with the following interfaces:

  • json.Marshaler and json.Unmarshaler (by gogo's jsonpb)
  • sql.Scanner and sql/driver.Valuer (by gogo's jsonpb)
  • bson.Marshaler and bson.Unmarshaler (by structbson)

Drop-in example

Please take ./example a look.

syntax = "proto3";
package example;

import "google/protobuf/struct.proto";

message MyMessage {
    google.protobuf.Struct payload = 1;
}

And please take ./example/gen.sh a look as well. There is how to tell the gogo output plugin to replace the Struct with our one.

./gen.sh

BSON Codec

Convert the gogo's types.Struct from and to bson

MongoDB example

package main

import (
    "context"
    "github.com/gogo/protobuf/types"
    "github.com/rueian/gogo-struct-codec/structbson"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
)

func main() {
    
    // MUST first replace bson's DefaultRegistry with the one in structbson
    bson.DefaultRegistry = structbson.DefaultRegistry

    s := types.Struct{Fields:map[string]*types.Value{
        "_id": {Kind: &types.Value_StringValue{StringValue: "str"}},
    }}
    
    // connect mongoclient

    res, err := mongoclient.Database("db").Collection("collection").InsertOne(ctx, s)
    
    // handle err and response 
}

BSON manipulation

more details in test cases

About

codec of the Well Known google.protobuf.Struct type which generated by gogo protobuf

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published