/
any_conv.go
86 lines (73 loc) · 2.35 KB
/
any_conv.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
84
85
86
package funcspec
import (
"reflect"
"github.com/hashicorp/go-argmapper"
"github.com/hashicorp/opaqueany"
"google.golang.org/protobuf/proto"
)
// anyConvGen is an argmapper.ConverterGenFunc that dynamically creates
// converters to *opaqueany.Any for types that implement proto.Message. This
// allows automatic conversion to *opaqueopaqueany.Any.
//
// This is automatically injected for all funcspec.Func calls.
func anyConvGen(v argmapper.Value) (*argmapper.Func, error) {
anyType := reflect.TypeOf((*opaqueany.Any)(nil))
protoMessageType := reflect.TypeOf((*proto.Message)(nil)).Elem()
if !v.Type.Implements(protoMessageType) {
return nil, nil
}
// We take this value as our input.
inputSet, err := argmapper.NewValueSet([]argmapper.Value{v})
if err != nil {
return nil, err
}
// Generate an int with the subtype of the string value
outputSet, err := argmapper.NewValueSet([]argmapper.Value{{
Name: v.Name,
Type: anyType,
Subtype: string(proto.MessageName(reflect.Zero(v.Type).Interface().(proto.Message))),
}})
if err != nil {
return nil, err
}
return argmapper.BuildFunc(inputSet, outputSet, func(in, out *argmapper.ValueSet) error {
anyVal, err := opaqueany.New(inputSet.Typed(v.Type).Value.Interface().(proto.Message))
if err != nil {
return err
}
outputSet.Typed(anyType).Value = reflect.ValueOf(anyVal)
return nil
})
}
type protoToAny interface {
Proto() *opaqueany.Any
}
func fromConvGen(v argmapper.Value) (*argmapper.Func, error) {
anyType := reflect.TypeOf((*opaqueany.Any)(nil))
protoMessageType := reflect.TypeOf((*protoToAny)(nil)).Elem()
if !v.Type.Implements(protoMessageType) {
return nil, nil
}
// We take this value as our input.
inputSet, err := argmapper.NewValueSet([]argmapper.Value{v})
if err != nil {
return nil, err
}
// Generate an int with the subtype of the string value
outputSet, err := argmapper.NewValueSet([]argmapper.Value{{
Name: v.Name,
Type: anyType,
Subtype: string(proto.MessageName(reflect.Zero(v.Type).Interface().(proto.Message))),
}})
if err != nil {
return nil, err
}
return argmapper.BuildFunc(inputSet, outputSet, func(in, out *argmapper.ValueSet) error {
anyVal, err := opaqueany.New(inputSet.Typed(v.Type).Value.Interface().(proto.Message))
if err != nil {
return err
}
outputSet.Typed(anyType).Value = reflect.ValueOf(anyVal)
return nil
})
}