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
- Host: GitHub
- URL: https://github.com/rueian/gogo-struct-codec
- Owner: rueian
- Created: 2019-10-12T19:35:18.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2022-11-08T07:23:12.000Z (over 3 years ago)
- Last Synced: 2025-01-23T05:29:17.414Z (over 1 year ago)
- Topics: bson, codec, gogo, golang, json, mongo, protobuf
- Language: Go
- Size: 28.3 KB
- Stars: 1
- Watchers: 3
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
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)