Created
August 6, 2020 05:55
-
-
Save dschowta/2546e49d7c28586c1875e5914f025b01 to your computer and use it in GitHub Desktop.
golang: grpc: interface or map type conversion to protobuf struct using protojson .
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks