-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconversion.go
65 lines (57 loc) · 1.49 KB
/
conversion.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 lib
import (
"encoding/json"
"github.com/golang/protobuf/ptypes/any"
"github.com/golang/protobuf/ptypes/wrappers"
"golang.org/x/exp/constraints"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
)
func IntToBool[T constraints.Signed](a T) bool {
switch a {
case 0, -1:
return false
}
return true
}
func ConvertAnyToInterface(anyValue *any.Any) (interface{}, error) {
var value interface{}
bytesValue := &wrappers.BytesValue{}
err := anypb.UnmarshalTo(anyValue, bytesValue, proto.UnmarshalOptions{})
if err != nil {
return value, err
}
uErr := json.Unmarshal(bytesValue.Value, &value)
if uErr != nil {
return value, uErr
}
return value, nil
}
func ConvertInterfaceToAny(v interface{}) (*any.Any, error) {
anyValue := &any.Any{}
bytes, _ := json.Marshal(v)
bytesValue := &wrappers.BytesValue{
Value: bytes,
}
err := anypb.MarshalFrom(anyValue, bytesValue, proto.MarshalOptions{})
return anyValue, err
}
func MustConvertInterfaceToAny(v interface{}) *any.Any {
anyValue := &any.Any{}
bytes, _ := json.Marshal(v)
bytesValue := &wrappers.BytesValue{
Value: bytes,
}
anypb.MarshalFrom(anyValue, bytesValue, proto.MarshalOptions{})
return anyValue
}
func MustConvertAnyToInterface(anyValue *any.Any) interface{} {
var value interface{}
bytesValue := &wrappers.BytesValue{}
err := anypb.UnmarshalTo(anyValue, bytesValue, proto.UnmarshalOptions{})
if err != nil {
return value
}
json.Unmarshal(bytesValue.Value, &value)
return value
}