-
Notifications
You must be signed in to change notification settings - Fork 14
/
serialization.go
404 lines (345 loc) · 8.97 KB
/
serialization.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package egoscale
import (
"encoding/base64"
"fmt"
"log"
"net"
"net/url"
"reflect"
"strconv"
"strings"
)
func csQuotePlus(s string) string {
s = strings.ReplaceAll(s, "+", "%20")
// This line is used to safeguard the "*" when producing the signature
s = strings.ReplaceAll(s, "%2A", "*")
return s
}
func csEncode(s string) string {
return csQuotePlus(url.QueryEscape(s))
}
// info returns the meta info of a command
//
// command is not a Command so it's easier to Test
func info(command interface{}) (*CommandInfo, error) {
typeof := reflect.TypeOf(command)
// Going up the pointer chain to find the underlying struct
for typeof.Kind() == reflect.Ptr {
typeof = typeof.Elem()
}
field, ok := typeof.FieldByName("_")
if !ok {
return nil, fmt.Errorf(`missing meta ("_") field in %#v`, command)
}
name, nameOk := field.Tag.Lookup("name")
description, _ := field.Tag.Lookup("description")
if !nameOk {
return nil, fmt.Errorf(`missing "name" key in the tag string of %#v`, command)
}
info := &CommandInfo{
Name: name,
Description: description,
}
return info, nil
}
// prepareValues uses a command to build a POST request
//
// command is not a Command so it's easier to Test
func prepareValues(prefix string, command interface{}) (url.Values, error) {
params := url.Values{}
value := reflect.ValueOf(command)
typeof := reflect.TypeOf(command)
// Going up the pointer chain to find the underlying struct
for typeof.Kind() == reflect.Ptr {
typeof = typeof.Elem()
value = value.Elem()
}
// Checking for nil commands
if !value.IsValid() {
return nil, fmt.Errorf("cannot serialize the invalid value %#v", command)
}
for i := 0; i < typeof.NumField(); i++ {
field := typeof.Field(i)
if field.Name == "_" {
continue
}
val := value.Field(i)
tag := field.Tag
var err error
var name string
var value interface{}
if json, ok := tag.Lookup("json"); ok {
n, required := ExtractJSONTag(field.Name, json)
name = prefix + n
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
value, err = prepareInt(val.Int(), required)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
value, err = prepareUint(val.Uint(), required)
case reflect.Float32, reflect.Float64:
value, err = prepareFloat(val.Float(), required)
case reflect.String:
value, err = prepareString(val.String(), required)
case reflect.Bool:
value, err = prepareBool(val.Bool(), required)
case reflect.Map:
if val.Len() == 0 {
if required {
err = fmt.Errorf("field is required, got empty map")
}
} else {
value, err = prepareMap(name, val.Interface())
}
case reflect.Ptr:
value, err = preparePtr(field.Type.Elem().Kind(), val, required)
case reflect.Slice:
value, err = prepareSlice(name, field.Type, val, required)
case reflect.Struct:
value, err = prepareStruct(val.Interface(), required)
default:
if required {
err = fmt.Errorf("unsupported type")
}
}
} else {
switch val.Kind() {
case reflect.Struct:
value, err = prepareEmbedStruct(val.Interface())
default:
log.Printf("[SKIP] %s.%s no json label found", typeof.Name(), field.Name)
}
}
if err != nil {
return nil, fmt.Errorf("%s.%s (%v) %s", typeof.Name(), field.Name, val.Kind(), err)
}
switch v := value.(type) {
case *string:
if name != "" && v != nil {
params.Set(name, *v)
}
case url.Values:
for k, xs := range v {
for _, x := range xs {
params.Add(k, x)
}
}
}
}
return params, nil
}
func prepareInt(v int64, required bool) (*string, error) {
if v == 0 {
if required {
return nil, fmt.Errorf("field is required, got %d", v)
}
return nil, nil
}
value := strconv.FormatInt(v, 10)
return &value, nil
}
func prepareUint(v uint64, required bool) (*string, error) {
if v == 0 {
if required {
return nil, fmt.Errorf("field is required, got %d", v)
}
return nil, nil
}
value := strconv.FormatUint(v, 10)
return &value, nil
}
func prepareFloat(v float64, required bool) (*string, error) {
if v == 0 {
if required {
return nil, fmt.Errorf("field is required, got %f", v)
}
return nil, nil
}
value := strconv.FormatFloat(v, 'f', -1, 64)
return &value, nil
}
func prepareString(v string, required bool) (*string, error) {
if v == "" {
if required {
return nil, fmt.Errorf("field is required, got %q", v)
}
return nil, nil
}
return &v, nil
}
func prepareBool(v bool, required bool) (*string, error) {
value := strconv.FormatBool(v)
if !v {
if required {
return &value, nil
}
return nil, nil
}
return &value, nil
}
func prepareList(prefix string, slice interface{}) (url.Values, error) {
params := url.Values{}
value := reflect.ValueOf(slice)
for i := 0; i < value.Len(); i++ {
ps, err := prepareValues(fmt.Sprintf("%s[%d].", prefix, i), value.Index(i).Interface())
if err != nil {
return nil, err
}
for k, xs := range ps {
for _, x := range xs {
params.Add(k, x)
}
}
}
return params, nil
}
func prepareMap(prefix string, m interface{}) (url.Values, error) {
value := url.Values{}
v := reflect.ValueOf(m)
for i, key := range v.MapKeys() {
var keyName string
var keyValue string
switch key.Kind() {
case reflect.String:
keyName = key.String()
default:
return value, fmt.Errorf("only map[string]string are supported (XXX)")
}
val := v.MapIndex(key)
switch val.Kind() {
case reflect.String:
keyValue = val.String()
default:
return value, fmt.Errorf("only map[string]string are supported (XXX)")
}
value.Set(fmt.Sprintf("%s[%d].%s", prefix, i, keyName), keyValue)
}
return value, nil
}
func preparePtr(kind reflect.Kind, val reflect.Value, required bool) (*string, error) {
if val.IsNil() {
if required {
return nil, fmt.Errorf("field is required, got empty ptr")
}
return nil, nil
}
switch kind {
case reflect.Bool:
return prepareBool(val.Elem().Bool(), true)
case reflect.Struct:
return prepareStruct(val.Interface(), required)
default:
return nil, fmt.Errorf("kind %v is not supported as a ptr", kind)
}
}
func prepareSlice(name string, fieldType reflect.Type, val reflect.Value, required bool) (interface{}, error) {
switch fieldType.Elem().Kind() {
case reflect.Uint8:
switch fieldType {
case reflect.TypeOf(net.IPv4zero):
ip := (net.IP)(val.Bytes())
if ip == nil || ip.Equal(net.IP{}) {
if required {
return nil, fmt.Errorf("field is required, got zero IPv4 address")
}
} else {
value := ip.String()
return &value, nil
}
case reflect.TypeOf(MAC48(0, 0, 0, 0, 0, 0)):
mac := val.Interface().(MACAddress)
s := mac.String()
if s == "" {
if required {
return nil, fmt.Errorf("field is required, got empty MAC address")
}
} else {
return &s, nil
}
default:
if val.Len() == 0 {
if required {
return nil, fmt.Errorf("field is required, got empty slice")
}
} else {
value := base64.StdEncoding.EncodeToString(val.Bytes())
return &value, nil
}
}
case reflect.String:
if val.Len() == 0 {
if required {
return nil, fmt.Errorf("field is required, got empty slice")
}
} else {
elems := make([]string, 0, val.Len())
for i := 0; i < val.Len(); i++ {
// XXX what if the value contains a comma? Double encode?
s := val.Index(i).String()
elems = append(elems, s)
}
value := strings.Join(elems, ",")
return &value, nil
}
default:
switch fieldType.Elem() {
case reflect.TypeOf(CIDR{}), reflect.TypeOf(UUID{}):
if val.Len() == 0 {
if required {
return nil, fmt.Errorf("field is required, got empty slice")
}
} else {
v := reflect.ValueOf(val.Interface())
ss := make([]string, val.Len())
for i := 0; i < v.Len(); i++ {
e := v.Index(i).Interface()
s, ok := e.(fmt.Stringer)
if !ok {
return nil, fmt.Errorf("not a String, %T", e)
}
ss[i] = s.String()
}
value := strings.Join(ss, ",")
return &value, nil
}
default:
if val.Len() == 0 {
if required {
return nil, fmt.Errorf("field is required, got empty slice")
}
} else {
return prepareList(name, val.Interface())
}
}
}
return nil, nil
}
func prepareStruct(i interface{}, required bool) (*string, error) {
s, ok := i.(fmt.Stringer)
if !ok {
return nil, fmt.Errorf("struct field not a Stringer")
}
if s == nil {
if required {
return nil, fmt.Errorf("field is required, got %#v", s)
}
}
return prepareString(s.String(), required)
}
func prepareEmbedStruct(i interface{}) (url.Values, error) {
return prepareValues("", i)
}
// ExtractJSONTag returns the variable name or defaultName as well as if the field is required (!omitempty)
func ExtractJSONTag(defaultName, jsonTag string) (string, bool) {
tags := strings.Split(jsonTag, ",")
name := tags[0]
required := true
for _, tag := range tags {
if tag == "omitempty" {
required = false
}
}
if name == "" || name == "omitempty" {
name = defaultName
}
return name, required
}