forked from opsee/protobuf
/
any.go
83 lines (68 loc) · 1.61 KB
/
any.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package types
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"github.com/gogo/protobuf/jsonpb"
proto "github.com/gogo/protobuf/proto"
)
var AnyTypeRegistry = NewTypesRegistry()
// UnmarshalAny unmarshals an Any object based on its TypeUrl type hint.
func UnmarshalAny(any *Any) (interface{}, error) {
class := any.TypeUrl
bytes := any.Value
if class, ok := AnyTypeRegistry.Get(class); !ok {
return nil, fmt.Errorf("Couldn't find type in registry")
} else {
instance := reflect.New(class).Interface()
err := proto.Unmarshal(bytes, instance.(proto.Message))
if err != nil {
return nil, err
}
return instance, nil
}
}
// MarshalAny uses reflection to marshal an interface{} into an Any object and
// sets up its TypeUrl type hint.
func MarshalAny(i interface{}) (*Any, error) {
msg, ok := i.(proto.Message)
if !ok {
err := fmt.Errorf("Unable to convert to proto.Message: %v", i)
return nil, err
}
bytes, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
return &Any{
TypeUrl: reflect.ValueOf(i).Elem().Type().Name(),
Value: bytes,
}, nil
}
// marshal any to json
func (a *Any) MarshalJSON() ([]byte, error) {
obj, err := UnmarshalAny(a)
if err != nil {
return []byte{}, err
}
bytes, err := json.Marshal(obj)
if err != nil {
return []byte{}, err
}
return bytes, nil
}
func (a *Any) Scan(src interface{}) error {
var source []byte
switch src.(type) {
case []byte:
source = src.([]byte)
default:
return fmt.Errorf("Received unsupported type to Scan(): %v", src)
}
err := jsonpb.Unmarshal(bytes.NewBuffer(source), a)
if err != nil {
return err
}
return nil
}