-
Notifications
You must be signed in to change notification settings - Fork 432
/
utils.go
65 lines (54 loc) · 1.65 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package protoutils
import (
"bytes"
"github.com/ghodss/yaml"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/rotisserie/eris"
)
var (
jsonpbMarshaler = &jsonpb.Marshaler{OrigName: false}
jsonpbMarshalerEmitZeroValues = &jsonpb.Marshaler{OrigName: false, EmitDefaults: true}
NilStructError = eris.New("cannot unmarshal nil struct")
)
// this function is designed for converting go object (that is not a proto.Message) into a
// pb Struct, based on json struct tags
func MarshalStruct(m proto.Message) (*structpb.Struct, error) {
data, err := MarshalBytes(m)
if err != nil {
return nil, err
}
var pb structpb.Struct
err = jsonpb.UnmarshalString(string(data), &pb)
return &pb, err
}
func MarshalStructEmitZeroValues(m proto.Message) (*structpb.Struct, error) {
data, err := MarshalBytesEmitZeroValues(m)
if err != nil {
return nil, err
}
var pb structpb.Struct
err = jsonpb.UnmarshalString(string(data), &pb)
return &pb, err
}
func MarshalBytes(pb proto.Message) ([]byte, error) {
buf := &bytes.Buffer{}
err := jsonpbMarshaler.Marshal(buf, pb)
return buf.Bytes(), err
}
func MarshalBytesEmitZeroValues(pb proto.Message) ([]byte, error) {
buf := &bytes.Buffer{}
err := jsonpbMarshalerEmitZeroValues.Marshal(buf, pb)
return buf.Bytes(), err
}
func UnmarshalBytes(data []byte, into proto.Message) error {
return jsonpb.Unmarshal(bytes.NewBuffer(data), into)
}
func UnmarshalYaml(data []byte, into proto.Message) error {
jsn, err := yaml.YAMLToJSON([]byte(data))
if err != nil {
return err
}
return jsonpb.Unmarshal(bytes.NewBuffer(jsn), into)
}