Skip to content

Instantly share code, notes, and snippets.

@dschowta
Created August 6, 2020 05:55
Show Gist options
  • Save dschowta/2546e49d7c28586c1875e5914f025b01 to your computer and use it in GitHub Desktop.
Save dschowta/2546e49d7c28586c1875e5914f025b01 to your computer and use it in GitHub Desktop.
golang: grpc: interface or map type conversion to protobuf struct using protojson .
// Conversion of interface{} or map[string]interface{} types to protobuf struct ("google/protobuf/struct.proto").
package codec
import (
"encoding/json"
structpb "github.com/golang/protobuf/ptypes/struct"
"google.golang.org/protobuf/encoding/protojson"
)
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)
}
@MorPolani-Zoomin
Copy link

Thanks!

@rsachin93
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment