forked from raystack/meteor
/
structmap.go
184 lines (155 loc) · 4.78 KB
/
structmap.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package structmap
import (
"encoding/json"
"fmt"
"reflect"
"time"
v1beta2 "github.com/goto/meteor/models/gotocompany/assets/v1beta2"
"github.com/mitchellh/mapstructure"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
func AsMap(v interface{}) (interface{}, error) {
// Cannot use mapstructure here because of
// 1. https://github.com/mitchellh/mapstructure/issues/249
// 2. Handling for fields with type *timestamp.Timestamp
var (
data []byte
err error
)
if m, ok := v.(proto.Message); ok {
data, err = protojson.MarshalOptions{UseProtoNames: true}.Marshal(m)
} else {
data, err = json.Marshal(v)
}
if err != nil {
return nil, fmt.Errorf("structmap: %T as map: marshal: %w", v, err)
}
var res interface{}
if err := json.Unmarshal(data, &res); err != nil {
return nil, fmt.Errorf("structmap: %T as map: unmarshal: %w", v, err)
}
return res, nil
}
func AsStruct(input, output interface{}) error {
return AsStructWithTag("json", input, output)
}
func AsStructWithTag(tagName string, input, output interface{}) error {
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(
checkAssetDataHookFunc(),
stringToTimestampHookFunc(time.RFC3339),
timeToTimestampHookFunc(),
mapstructure.StringToTimeHookFunc(time.RFC3339),
mapstructure.StringToTimeDurationHookFunc(),
mapToAttributesHookFunc(),
mapToAnyPBHookFunc(),
),
WeaklyTypedInput: true,
ErrorUnused: true,
ZeroFields: true,
Result: output,
TagName: tagName,
})
if err != nil {
return fmt.Errorf("structmap: decode into %T: create decoder: %w", output, err)
}
if err := dec.Decode(input); err != nil {
return fmt.Errorf("structmap: decode as struct: %w", err)
}
return nil
}
func checkAssetDataHookFunc() mapstructure.DecodeHookFuncType {
return func(_, t reflect.Type, data interface{}) (interface{}, error) {
if t != reflect.TypeOf(v1beta2.Asset{}) && t != reflect.TypeOf(&v1beta2.Asset{}) {
return data, nil
}
m, ok := data.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("mapstructure check asset: unexpected type: %T", data)
}
if _, ok := m["data"].(map[string]interface{}); !ok {
return nil, fmt.Errorf("mapstructure check asset data: unexpected type: %T", m["data"])
}
return data, nil
}
}
// stringToTimestampHookFunc returns a DecodeHookFunc that converts
// strings to timestamppb.Timestamp.
func stringToTimestampHookFunc(layout string) mapstructure.DecodeHookFuncType {
return func(_, t reflect.Type, data interface{}) (interface{}, error) {
s, ok := data.(string)
if !ok {
return data, nil
}
if t != reflect.TypeOf(timestamppb.Timestamp{}) && t != reflect.TypeOf(×tamppb.Timestamp{}) {
return data, nil
}
// Convert it by parsing
ts, err := time.Parse(layout, s)
if err != nil {
return nil, fmt.Errorf("mapstructure string to timestamp hook: %w", err)
}
return timestamppb.New(ts), nil
}
}
func timeToTimestampHookFunc() mapstructure.DecodeHookFuncType {
return func(_, t reflect.Type, data interface{}) (interface{}, error) {
ts, ok := data.(time.Time)
if !ok {
return data, nil
}
if t != reflect.TypeOf(timestamppb.Timestamp{}) && t != reflect.TypeOf(×tamppb.Timestamp{}) {
return data, nil
}
return timestamppb.New(ts), nil
}
}
func mapToAttributesHookFunc() mapstructure.DecodeHookFuncType {
return func(_, t reflect.Type, data interface{}) (interface{}, error) {
m, ok := data.(map[string]interface{})
if !ok {
return data, nil
}
if t != reflect.TypeOf(&structpb.Struct{}) && t != reflect.TypeOf(structpb.Struct{}) {
return data, nil
}
return structpb.NewStruct(m)
}
}
func mapToAnyPBHookFunc() mapstructure.DecodeHookFuncType {
failure := func(step string, err error) (interface{}, error) {
return nil, fmt.Errorf("mapstructure map to anypb hook: %s: %w", step, err)
}
return func(_, t reflect.Type, data interface{}) (interface{}, error) {
m, ok := data.(map[string]interface{})
if !ok {
return data, nil
}
if t != reflect.TypeOf(anypb.Any{}) && t != reflect.TypeOf(&anypb.Any{}) {
return data, nil
}
typ, ok := m["@type"].(string)
if !ok {
return data, nil
}
msgtyp, err := protoregistry.GlobalTypes.FindMessageByURL(typ)
if err != nil {
return failure("resolve type", err)
}
msg := msgtyp.New().Interface()
delete(m, "@type")
if err := AsStruct(m, &msg); err != nil {
return failure("decode", err)
}
dataAny, err := anypb.New(msg)
if err != nil {
return failure("marshal as any", err)
}
return dataAny, nil
}
}