An open API service indexing awesome lists of open source software.

https://github.com/rueian/gogo-struct-codec

codec of the Well Known google.protobuf.Struct type which generated by gogo protobuf
https://github.com/rueian/gogo-struct-codec

bson codec gogo golang json mongo protobuf

Last synced: about 2 months ago
JSON representation

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

Awesome Lists containing this project

README

          

# gogo-struct-codec

codec of the Well Known `google.protobuf.Struct` type which generated by [gogo protobuf](https://github.com/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](./example) a look.

```proto
syntax = "proto3";
package example;

import "google/protobuf/struct.proto";

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

And please take [./example/gen.sh](./example/gen.sh) a look as well. There is how to tell the gogo output plugin to replace the `Struct` with our one.
```shell script
./gen.sh
```

## BSON Codec

Convert the gogo's `types.Struct` from and to [bson](https://github.com/mongodb/mongo-go-driver)

### MongoDB example

```go
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](./structbson/main_test.go)