...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package conversion
17
18 import (
19 "bytes"
20 "errors"
21
22 "github.com/golang/protobuf/jsonpb"
23 "github.com/golang/protobuf/proto"
24 pstruct "github.com/golang/protobuf/ptypes/struct"
25 )
26
27
28
29
30 func MessageToStruct(msg proto.Message) (*pstruct.Struct, error) {
31 if msg == nil {
32 return nil, errors.New("nil message")
33 }
34
35 buf := &bytes.Buffer{}
36 if err := (&jsonpb.Marshaler{OrigName: true}).Marshal(buf, msg); err != nil {
37 return nil, err
38 }
39
40 pbs := &pstruct.Struct{}
41 if err := jsonpb.Unmarshal(buf, pbs); err != nil {
42 return nil, err
43 }
44
45 return pbs, nil
46 }
47
48
49 func StructToMessage(pbst *pstruct.Struct, out proto.Message) error {
50 if pbst == nil {
51 return errors.New("nil struct")
52 }
53
54 buf := &bytes.Buffer{}
55 if err := (&jsonpb.Marshaler{OrigName: true}).Marshal(buf, pbst); err != nil {
56 return err
57 }
58
59 return jsonpb.Unmarshal(buf, out)
60 }
61
View as plain text