codec of the Well Known google.protobuf.Struct
type which generated by gogo protobuf
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
andjson.Unmarshaler
(by gogo'sjsonpb
)sql.Scanner
andsql/driver.Valuer
(by gogo'sjsonpb
)bson.Marshaler
andbson.Unmarshaler
(bystructbson
)
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
Convert the gogo's types.Struct
from and to bson
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
}