generated from alexejk/go-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdecode.go
426 lines (347 loc) · 9.83 KB
/
decode.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package xmlrpc
import (
"encoding/base64"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
const (
errFormatInvalidFieldType = "invalid field type: expected '%s', got '%s'"
errFormatInvalidFieldTypeOrType = "invalid field type: expected '%s' or '%s', got '%s'"
errFormatInvalidMapKeyTypeForStruct = "invalid map key type: must be 'string' when decoding structs into a map, got '%s'"
float64BitSize = 64
)
// Decoder implementations provide mechanisms for parsing of XML-RPC responses to native data-types.
type Decoder interface {
DecodeRaw(body []byte, v interface{}) error
Decode(response *Response, v interface{}) error
DecodeFault(response *Response) *Fault
}
// StdDecoder is the default implementation of the Decoder interface.
type StdDecoder struct {
skipUnknownFields bool
}
func (d *StdDecoder) DecodeRaw(body []byte, v interface{}) error {
response, err := NewResponse(body)
if err != nil {
return err
}
if response.Fault != nil {
return d.decodeFault(response.Fault)
}
return d.Decode(response, v)
}
func (d *StdDecoder) Decode(response *Response, v interface{}) error {
// Validate that v has same number of public fields as response params
if err := fieldsMustEqual(v, len(response.Params)); err != nil {
return err
}
vElem := reflect.Indirect(reflect.ValueOf(v))
for i, param := range response.Params {
field := vElem.Field(i)
if err := d.decodeValue(¶m.Value, field); err != nil {
return err
}
}
return nil
}
func (d *StdDecoder) DecodeFault(response *Response) *Fault {
if response.Fault == nil {
return nil
}
return d.decodeFault(response.Fault)
}
func (d *StdDecoder) decodeFault(fault *ResponseFault) *Fault {
f := &Fault{}
for _, m := range fault.Value.Struct {
switch m.Name {
case "faultCode":
if m.Value.Int != nil {
f.Code, _ = strconv.Atoi(*m.Value.Int)
} else if m.Value.Int4 != nil {
f.Code, _ = strconv.Atoi(*m.Value.Int4)
} else {
f.Code = 0 // Unknown fault code
}
case "faultString":
if m.Value.String != nil {
f.String = *m.Value.String
}
}
}
return f
}
func (d *StdDecoder) decodeValue(value *ResponseValue, field reflect.Value) error {
field = indirect(field)
var val interface{}
var err error
switch {
case value.Int != nil:
val, err = d.decodeInt(*value.Int)
case value.Int4 != nil:
val, err = d.decodeInt(*value.Int4)
case value.Double != nil:
val, err = d.decodeDouble(*value.Double)
case value.Boolean != nil:
val, err = d.decodeBoolean(*value.Boolean)
case value.String != nil:
val, err = *value.String, nil
case value.Base64 != nil:
val, err = d.decodeBase64(*value.Base64)
case value.DateTime != nil:
val, err = d.decodeDateTime(*value.DateTime)
// Array decoding
case value.Array != nil:
fieldKind := field.Kind()
// When dealing with nested arrays of []any type, initial kind for the nested array will be reflect.Interface
if fieldKind == reflect.Interface {
// Create a new []interface{} and assign it to field
fieldType := reflect.SliceOf(reflect.TypeOf((*interface{})(nil)).Elem())
fieldKind = reflect.Slice
field.Set(reflect.MakeSlice(fieldType, 0, 0))
}
if fieldKind != reflect.Slice {
return fmt.Errorf(errFormatInvalidFieldType, reflect.Slice.String(), field.Kind().String())
}
values := value.Array.Values
if len(values) == 0 {
val, err = nil, nil
break
}
slice := reflect.MakeSlice(reflect.TypeOf(field.Interface()), len(values), len(values))
for i, v := range values {
item := slice.Index(i)
if err := d.decodeValue(v, item); err != nil {
return fmt.Errorf("failed decoding array item at index %d: %w", i, err)
}
}
val = slice.Interface()
// Struct decoding
case len(value.Struct) != 0:
fieldKind := field.Kind()
fieldType := field.Type()
if fieldKind == reflect.Interface {
// Create a new map[string]any and assign it to field
fieldType = reflect.TypeOf(map[string]any{})
fieldKind = reflect.Map
field.Set(reflect.MakeMap(fieldType))
field = field.Elem() // As the field is an interface, need to unwrap it
}
if fieldKind != reflect.Struct && fieldKind != reflect.Map {
return fmt.Errorf(errFormatInvalidFieldTypeOrType, reflect.Struct.String(), reflect.Map.String(), fieldKind.String())
}
// If we are targeting a map, it should be initialized
if fieldKind == reflect.Map {
if kt := fieldType.Key().Kind(); kt != reflect.String {
return fmt.Errorf(errFormatInvalidMapKeyTypeForStruct, kt.String())
}
if field.IsNil() {
field.Set(reflect.MakeMap(field.Type()))
}
}
for _, m := range value.Struct {
if fieldKind == reflect.Map {
mapKey := reflect.ValueOf(m.Name)
f := reflect.New(fieldType.Elem()).Elem()
if err := d.decodeValue(&m.Value, f); err != nil {
return fmt.Errorf("failed decoding struct member '%s': %w", m.Name, err)
}
field.SetMapIndex(mapKey, f)
} else {
// Upper-case the name
fName := structMemberToFieldName(m.Name)
f := findFieldByNameOrTag(field, fName)
if !f.IsValid() {
if d.skipUnknownFields {
continue
}
return fmt.Errorf("cannot find field '%s' on struct", fName)
}
if err := d.decodeValue(&m.Value, f); err != nil {
return fmt.Errorf("failed decoding struct member '%s': %w", m.Name, err)
}
}
}
default:
// Default to inner string (raw XML)
val, err = value.RawXML, nil
}
if err != nil {
return err
}
if val != nil {
// Assign if directly assignable, or convert to type if convertible
rVal := reflect.ValueOf(val)
if rVal.Type().AssignableTo(field.Type()) {
field.Set(rVal)
} else {
if !rVal.Type().ConvertibleTo(field.Type()) {
return fmt.Errorf("type '%s' cannot be assigned a value of type '%s'", field.Type().String(), rVal.Type().String())
}
field.Set(rVal.Convert(field.Type()))
}
}
return nil
}
func (d *StdDecoder) decodeInt(value string) (int, error) {
if value == "" {
return 0, nil
}
return strconv.Atoi(value)
}
func (d *StdDecoder) decodeDouble(value string) (float64, error) {
if value == "" {
return 0.0, nil
}
return strconv.ParseFloat(value, float64BitSize)
}
func (d *StdDecoder) decodeBoolean(value string) (bool, error) {
switch value {
case "1", "true", "TRUE", "True":
return true, nil
case "0", "false", "FALSE", "False":
return false, nil
case "":
return false, nil
default:
return false, fmt.Errorf("unrecognized value '%s' for boolean", value)
}
}
func (d *StdDecoder) decodeBase64(value string) ([]byte, error) {
if value == "" {
return nil, nil
}
return base64.StdEncoding.DecodeString(value)
}
func (d *StdDecoder) decodeDateTime(value string) (time.Time, error) {
if value == "" {
return time.Time{}, nil
}
return time.Parse(time.RFC3339, value)
}
func findFieldByNameOrTag(field reflect.Value, fName string) reflect.Value {
typ := field.Type()
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
keyName := getFieldNameFromTag(&f, "xmlrpc")
// If tagged name matches search value - return
if keyName == fName {
return field.Field(i)
}
}
return field.FieldByName(fName)
}
func getFieldNameFromTag(f *reflect.StructField, tagName string) string {
var keyName string
if f.PkgPath != "" {
return keyName
}
tagValue := f.Tag.Get(tagName)
if tagValue == "" {
return keyName
}
// Determine the name of the field based on struct tag
if index := strings.Index(tagValue, ","); index != -1 {
if tagValue[:index] == "-" {
return keyName
}
if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" {
keyName = keyNameTagValue
}
return keyName
}
if tagValue != "" && tagValue != "-" {
keyName = tagValue
}
return keyName
}
func fieldsMustEqual(v interface{}, expectation int) error {
vElem := reflect.Indirect(reflect.ValueOf(v))
numFields := 0
for i := 0; i < vElem.NumField(); i++ {
if vElem.Field(i).CanInterface() {
numFields++
}
}
if numFields != expectation {
return fmt.Errorf("number of exported fields (%d) on response type doesnt match expectation (%d)", numFields, expectation)
}
return nil
}
func structMemberToFieldName(structName string) string {
b := new(strings.Builder)
capNext := true
for _, v := range structName {
if v >= 'A' && v <= 'Z' {
b.WriteRune(v)
}
if v >= '0' && v <= '9' {
b.WriteRune(v)
}
if v >= 'a' && v <= 'z' {
if capNext {
b.WriteString(strings.ToUpper(string(v)))
} else {
b.WriteRune(v)
}
}
if v == '_' || v == ' ' || v == '-' || v == '.' {
capNext = true
} else {
capNext = false
}
}
return b.String()
}
// indirect walks down v allocating pointers as needed,
// until it gets to a non-pointer.
//
// Adapted from encoding/json indirect() function
// https://golang.org/src/encoding/json/decode.go?#L480
func indirect(v reflect.Value) reflect.Value {
// After the first round-trip, we set v back to the original value to
// preserve the original RW flags contained in reflect.Value.
v0 := v
haveAddr := false
// If v is a named type and is addressable,
// start with its address, so that if the type has pointer methods,
// we find them.
if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
haveAddr = true
v = v.Addr()
}
for {
// Load value from interface, but only if the result will be
// usefully addressable.
if v.Kind() == reflect.Interface && !v.IsNil() {
e := v.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() {
haveAddr = false
v = e
continue
}
}
if v.Kind() != reflect.Ptr {
break
}
// Prevent infinite loop if v is an interface pointing to its own address:
// var v interface{}
// v = &v
if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v {
v = v.Elem()
break
}
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
if haveAddr {
v = v0 // restore original value after round-trip Value.Addr().Elem()
haveAddr = false
} else {
v = v.Elem()
}
}
return v
}