Skip to content

Commit

Permalink
feat(structutil): add protobuf struct util package
Browse files Browse the repository at this point in the history
  • Loading branch information
pinglin committed May 9, 2022
1 parent e81f88d commit d98c6e1
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
go.temporal.io/sdk v1.13.1
go.uber.org/zap v1.21.0
google.golang.org/grpc v1.42.0
google.golang.org/protobuf v1.27.1
)

require (
Expand All @@ -17,5 +18,4 @@ require (
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
google.golang.org/genproto v0.0.0-20211104193956-4c6863e31247 // indirect
google.golang.org/protobuf v1.27.1 // indirect
)
57 changes: 57 additions & 0 deletions structutil/structutil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package structutil

import (
"encoding/json"

"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
)

func BytesToInterface(bytes []byte) (interface{}, error) {
var obj map[string]interface{}
if err := json.Unmarshal(bytes, &obj); err != nil {
if err.Error() == "json: cannot unmarshal array into Go value of type map[string]interface {}" {
var objArray []map[string]interface{}
if err := json.Unmarshal(bytes, &objArray); err != nil {
return nil, err
}
return objArray, nil
}
}

return obj, nil
}

func MapToProtobufStruct(m map[string]interface{}) (*structpb.Struct, error) {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
s := &structpb.Struct{}
err = protojson.Unmarshal(b, s)
if err != nil {
return nil, err
}
return s, nil
}

func ProtobufStructToMap(s *structpb.Struct) (map[string]interface{}, error) {
b, err := protojson.Marshal(s)
if err != nil {
return nil, err
}
m := make(map[string]interface{})
err = json.Unmarshal(b, &m)
if err != nil {
return nil, err
}
return m, nil
}

func StructToProtobufStruct(s interface{}) (*structpb.Struct, error) {
return MapToProtobufStruct(s.(map[string]interface{}))
}

func ProtobufStructToStruct(s *structpb.Struct) (interface{}, error) {
return ProtobufStructToMap(s)
}

0 comments on commit d98c6e1

Please sign in to comment.