Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save vbratkev/12a3b2384aa04d859658bbd0cd68fcdf to your computer and use it in GitHub Desktop.

Select an option

Save vbratkev/12a3b2384aa04d859658bbd0cd68fcdf to your computer and use it in GitHub Desktop.

Revisions

  1. @dschowta dschowta created this gist Aug 6, 2020.
    42 changes: 42 additions & 0 deletions protobuf_struct_converter.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    // 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)
    }