-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.go
936 lines (782 loc) · 23.5 KB
/
request.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
package jsonapi
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"time"
)
const (
unsupportedStructTagMsg = "Unsupported jsonapi tag annotation, %s"
)
var (
// ErrInvalidTime is returned when a struct has a time.Time type field, but
// the JSON value was not a unix timestamp integer.
ErrInvalidTime = errors.New("only numbers can be parsed as dates, unix timestamps")
// ErrInvalidISO8601 is returned when a struct has a time.Time type field and includes
// "iso8601" in the tag spec, but the JSON value was not an ISO8601 timestamp string.
ErrInvalidISO8601 = errors.New("only strings can be parsed as dates, ISO8601 timestamps")
// ErrUnknownFieldNumberType is returned when the JSON value was a float
// (numeric) but the Struct field was a non numeric type (i.e. not int, uint,
// float, etc)
ErrUnknownFieldNumberType = errors.New("the struct field was not of a known number type")
// ErrInvalidType is returned when the given type is incompatible with the expected type.
ErrInvalidType = errors.New("invalid type provided") // I wish we used punctuation.
)
// ErrUnsupportedPtrType is returned when the Struct field was a pointer but
// the JSON value was of a different type
type ErrUnsupportedPtrType struct {
rf reflect.Value
t reflect.Type
structField reflect.StructField
}
func (eupt ErrUnsupportedPtrType) Error() string {
typeName := eupt.t.Elem().Name()
kind := eupt.t.Elem().Kind()
if kind.String() != "" && kind.String() != typeName {
typeName = fmt.Sprintf("%s (%s)", typeName, kind.String())
}
return fmt.Sprintf(
"jsonapi: Can't unmarshal %+v (%s) to struct field `%s`, which is a pointer to `%s`",
eupt.rf, eupt.rf.Type().Kind(), eupt.structField.Name, typeName,
)
}
func newErrUnsupportedPtrType(rf reflect.Value, t reflect.Type, structField reflect.StructField) error {
return ErrUnsupportedPtrType{rf, t, structField}
}
// UnmarshalPayload converts an io into a struct instance using jsonapi tags on
// struct fields. This method supports single request payloads only, at the
// moment. Bulk creates and updates are not supported yet.
//
// Will Unmarshal embedded and sideloaded payloads. The latter is only possible if the
// object graph is complete. That is, in the "relationships" data there are type and id,
// keys that correspond to records in the "included" array.
//
// For example you could pass it, in, req.Body and, model, a BlogPost
// struct instance to populate in an http handler,
//
// func CreateBlog(w http.ResponseWriter, r *http.Request) {
// blog := new(Blog)
//
// if err := jsonapi.UnmarshalPayload(r.Body, blog); err != nil {
// http.Error(w, err.Error(), 500)
// return
// }
//
// // ...do stuff with your blog...
//
// w.Header().Set("Content-Type", jsonapi.MediaType)
// w.WriteHeader(201)
//
// if err := jsonapi.MarshalPayload(w, blog); err != nil {
// http.Error(w, err.Error(), 500)
// }
// }
//
//
// Visit https://github.com/elasticpath/jsonapi#create for more info.
//
// model interface{} should be a pointer to a struct.
func UnmarshalPayload(in io.Reader, model interface{}) error {
payload := new(OnePayload)
var duplicate bytes.Buffer
tee := io.TeeReader(in, &duplicate)
if err := json.NewDecoder(tee).Decode(payload); err != nil {
return err
}
nulls := make(map[string]interface{})
if err := unmarshalShadow(duplicate, nulls); err != nil {
}
if payload.Included != nil {
includedMap := make(map[string]*ResourceObj)
for _, included := range payload.Included {
key := fmt.Sprintf("%s,%s", included.Type, included.ID)
includedMap[key] = included
}
return unmarshalNode(payload.Data, nulls, reflect.ValueOf(model), &includedMap)
}
return unmarshalNode(payload.Data, nulls, reflect.ValueOf(model), nil)
}
// UnmarshalManyPayload converts an io into a set of struct instances using
// jsonapi tags on the type's struct fields.
func UnmarshalManyPayload(in io.Reader, t reflect.Type) ([]interface{}, error) {
payload := new(ManyPayload)
if err := json.NewDecoder(in).Decode(payload); err != nil {
return nil, err
}
models := []interface{}{} // will be populated from the "data"
includedMap := map[string]*ResourceObj{} // will be populate from the "included"
if payload.Included != nil {
for _, included := range payload.Included {
key := fmt.Sprintf("%s,%s", included.Type, included.ID)
includedMap[key] = included
}
}
for _, data := range payload.Data {
model := reflect.New(t.Elem())
nulls := make(map[string]interface{})
err := unmarshalNode(data, nulls, model, &includedMap)
if err != nil {
return nil, err
}
models = append(models, model.Interface())
}
return models, nil
}
func unmarshalShadow(payload bytes.Buffer, data map[string]interface{}) (err error) {
v := new(NulledPayload)
if err := json.Unmarshal(payload.Bytes(), v); err != nil {
return err
}
for i := range v.Data.Attributes {
message := v.Data.Attributes[i]
if string(message) == "null" {
data[i] = v.Data.Attributes[i]
}
}
return nil
}
func unmarshalNode(data *ResourceObj, nulls map[string]interface{}, model reflect.Value, included *map[string]*ResourceObj) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("data is not a jsonapi representation of '%v'\n\n%v", model.Type(), r)
}
}()
modelValue := model.Elem()
modelType := modelValue.Type()
var er error
for i := 0; i < modelValue.NumField(); i++ {
fieldType := modelType.Field(i)
tag := fieldType.Tag.Get("jsonapi")
if tag == "" {
continue
}
fieldValue := modelValue.Field(i)
args := strings.Split(tag, ",")
if len(args) < 2 {
er = ErrBadJSONAPIStructTag
break
}
annotation := args[0]
switch {
case annotation == annotationPrimary:
if data.ID == "" {
continue
}
// Check the JSON API Type
if data.Type != args[1] {
er = fmt.Errorf(
"Trying to Unmarshal an object of type %#v, but %#v does not match",
data.Type,
args[1],
)
break
}
// ID will have to be transmitted as astring per the JSON API spec
v := reflect.ValueOf(data.ID)
// Deal with PTRS
var kind reflect.Kind
if fieldValue.Kind() == reflect.Ptr {
kind = fieldType.Type.Elem().Kind()
} else {
kind = fieldType.Type.Kind()
}
// Handle String case
if kind == reflect.String {
assign(fieldValue, v)
continue
}
// Value was not a string... only other supported type was a numeric,
// which would have been sent as a float value.
floatValue, err := strconv.ParseFloat(data.ID, 64)
if err != nil {
// Could not convert the value in the "id" attr to a float
er = ErrBadJSONAPIID
break
}
// Convert the numeric float to one of the supported ID numeric types
// (int[8,16,32,64] or uint[8,16,32,64])
idValue, err := handleNumeric(floatValue, fieldType.Type, fieldValue)
if err != nil {
// We had a JSON float (numeric), but our field was not one of the
// allowed numeric types
er = ErrBadJSONAPIID
break
}
assign(fieldValue, idValue)
case annotation == annotationAttribute:
attributes := data.Attributes
if attributes == nil || len(data.Attributes) == 0 {
continue
}
attribute := attributes[args[1]]
// continue if the attribute was not included in the request
if attribute == nil {
val, ok := nulls[args[1]]
if !ok {
continue
}
var model reflect.Value
if fieldValue.Kind() == reflect.Ptr {
model = reflect.New(fieldValue.Type().Elem())
} else {
model = reflect.New(fieldValue.Type())
}
// handle custom structs which need UnmarshalJSON to work.
method := model.MethodByName("UnmarshalJSON")
if !method.IsValid() {
continue
}
attribute = val
}
structField := fieldType
value, err := unmarshalAttribute(attribute, args, structField, fieldValue)
if err != nil {
er = err
break
}
assign(fieldValue, value)
case annotation == annotationMeta:
meta := data.Meta
if meta == nil || len(*meta) == 0 {
continue
}
m := (*meta)[args[1]]
// continue if the m was not included in the request
if m == nil {
continue
}
structField := fieldType
value, err := unmarshalAttribute(m, args, structField, fieldValue)
if err != nil {
er = err
break
}
assign(fieldValue, value)
case annotation == annotationRelation:
if data.Relationships == nil || data.Relationships[args[1]] == nil {
continue
}
isSlice := fieldValue.Type().Kind() == reflect.Slice
if isSlice {
// to-many relationship
relationship := new(RelationshipManyNode)
buf := bytes.NewBuffer(nil)
json.NewEncoder(buf).Encode(data.Relationships[args[1]])
json.NewDecoder(buf).Decode(relationship)
data := relationship.Data
models := reflect.New(fieldValue.Type()).Elem()
for _, n := range data {
m := reflect.New(fieldValue.Type().Elem().Elem())
nulls := make(map[string]interface{})
if err := unmarshalNode(
fullNode(n, included),
nulls,
m,
included,
); err != nil {
er = err
break
}
models = reflect.Append(models, m)
}
fieldValue.Set(models)
} else {
// to-one relationships
relationship := new(RelationshipOneNode)
buf := bytes.NewBuffer(nil)
json.NewEncoder(buf).Encode(
data.Relationships[args[1]],
)
json.NewDecoder(buf).Decode(relationship)
/*
http://jsonapi.org/format/#document-resource-object-relationships
http://jsonapi.org/format/#document-resource-object-linkage
relationship can have a data node set to null (e.g. to disassociate the relationship)
so unmarshal and set fieldValue only if data obj is not null
*/
if relationship.Data == nil {
continue
}
m := reflect.New(fieldValue.Type().Elem())
nulls := make(map[string]interface{})
if err := unmarshalNode(
fullNode(relationship.Data, included),
nulls,
m,
included,
); err != nil {
er = err
break
}
fieldValue.Set(m)
}
default:
er = fmt.Errorf(unsupportedStructTagMsg, annotation)
}
}
return er
}
func fullNode(n *ResourceObj, included *map[string]*ResourceObj) *ResourceObj {
includedKey := fmt.Sprintf("%s,%s", n.Type, n.ID)
if included != nil && (*included)[includedKey] != nil {
return (*included)[includedKey]
}
return n
}
// assign will take the value specified and assign it to the field; if
// field is expecting a ptr assign will assign a ptr.
func assign(field, value reflect.Value) {
value = reflect.Indirect(value)
if field.Kind() == reflect.Ptr {
// initialize pointer so it's value
// can be set by assignValue
field.Set(reflect.New(field.Type().Elem()))
field = field.Elem()
}
assignValue(field, value)
}
// assign assigns the specified value to the field,
// expecting both values not to be pointer types.
func assignValue(field, value reflect.Value) {
switch field.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
field.SetInt(value.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
field.SetUint(value.Uint())
case reflect.Float32, reflect.Float64:
field.SetFloat(value.Float())
case reflect.String:
field.SetString(value.String())
case reflect.Bool:
field.SetBool(value.Bool())
default:
field.Set(value)
}
}
// unmarshalAttribute will unmarshall each attribute field.
func unmarshalAttribute(
attribute interface{},
args []string,
structField reflect.StructField,
fieldValue reflect.Value) (value reflect.Value, err error) {
//value = reflect.ValueOf(attribute)
fieldType := structField.Type
value, err = handleField(attribute, args, fieldType, fieldValue)
switch {
case err == ErrInvalidType:
return reflect.Value{}, ErrInvalidType
case err == ErrInvalidISO8601:
return reflect.Value{}, ErrInvalidISO8601
case err != nil:
return reflect.Value{},
newErrUnsupportedPtrType(reflect.ValueOf(attribute), fieldType, structField)
}
return
}
// handleField parses each individual field given its type and value. The method allows for recursion when unmarshalling
// so we can traverse to primitive types.
func handleField(
attribute interface{},
args []string,
fieldType reflect.Type,
fieldValue reflect.Value) (value reflect.Value, err error) {
value = reflect.ValueOf(attribute)
switch fieldType.Kind() {
case reflect.Bool:
val, err := handleBool(attribute)
return reflect.ValueOf(val), err
case reflect.Int:
val, err := handleInt(attribute)
return reflect.ValueOf(val), err
case reflect.Int8:
val, err := handleInt8(attribute)
return reflect.ValueOf(val), err
case reflect.Int16:
val, err := handleInt16(attribute)
return reflect.ValueOf(val), err
case reflect.Int32:
val, err := handleInt32(attribute)
return reflect.ValueOf(val), err
case reflect.Int64:
val, err := handleInt64(attribute)
return reflect.ValueOf(val), err
case reflect.Uint:
val, err := handleUint(attribute)
return reflect.ValueOf(val), err
case reflect.Uint8:
val, err := handleUint8(attribute)
return reflect.ValueOf(val), err
case reflect.Uint16:
val, err := handleUint16(attribute)
return reflect.ValueOf(val), err
case reflect.Uint32:
val, err := handleUint32(attribute)
return reflect.ValueOf(val), err
case reflect.Uint64:
val, err := handleUint64(attribute)
return reflect.ValueOf(val), err
case reflect.Float32:
val, err := handleFloat32(attribute)
return reflect.ValueOf(val), err
case reflect.Float64:
val, err := handleFloat64(attribute)
return reflect.ValueOf(val), err
case reflect.String:
val, err := handleString(attribute, fieldType, fieldValue)
return reflect.ValueOf(val), err
case reflect.Slice:
switch reflect.TypeOf(fieldValue.Interface()).Elem().Kind() {
case reflect.Struct:
return handleStructSlice(attribute, fieldValue)
default:
return handleSlice(attribute, args, fieldType, fieldValue)
}
case reflect.Ptr:
return handlePointer(attribute, args, fieldType, fieldValue)
case reflect.Struct:
if fieldType.ConvertibleTo(reflect.TypeOf(time.Time{})) {
return handleTime(attribute, args, fieldValue)
}
return handleStruct(attribute, fieldValue)
case reflect.Map:
return handleMap(attribute, args, fieldType)
}
return
}
// handleBool
func handleBool(
attribute interface{}) (bool, error) {
if val, ok := attribute.(bool); ok {
return val, nil
}
return false, errors.New("invalid value to assign to boolean")
}
func handleNumeric(
attribute interface{},
fieldType reflect.Type,
fieldValue reflect.Value) (reflect.Value, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
var kind reflect.Kind
if fieldValue.Kind() == reflect.Ptr {
kind = fieldType.Elem().Kind()
} else {
kind = fieldType.Kind()
}
var numericValue reflect.Value
switch kind {
case reflect.Int:
n := int(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Int8:
n := int8(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Int16:
n := int16(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Int32:
n := int32(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Int64:
n := int64(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Uint:
n := uint(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Uint8:
n := uint8(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Uint16:
n := uint16(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Uint32:
n := uint32(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Uint64:
n := uint64(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Float32:
n := float32(floatValue)
numericValue = reflect.ValueOf(&n)
case reflect.Float64:
n := floatValue
numericValue = reflect.ValueOf(&n)
default:
return reflect.Value{}, ErrUnknownFieldNumberType
}
return numericValue, nil
}
// handleInt
func handleInt(attribute interface{}) (int, error) {
v := reflect.ValueOf(attribute)
floatValue, ok := v.Interface().(float64)
if !ok {
return 0, ErrInvalidType
}
return int(floatValue), nil
}
// handleInt8
func handleInt8(attribute interface{}) (int8, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return int8(floatValue), nil
}
// handleInt16
func handleInt16(attribute interface{}) (int16, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return int16(floatValue), nil
}
// handleInt32
func handleInt32(attribute interface{}) (int32, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return int32(floatValue), nil
}
// handleInt64
func handleInt64(attribute interface{}) (int64, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return int64(floatValue), nil
}
// handleUint
func handleUint(attribute interface{}) (uint, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return uint(floatValue), nil
}
// handleUint8
func handleUint8(attribute interface{}) (uint8, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return uint8(floatValue), nil
}
// handleUint16
func handleUint16(attribute interface{}) (uint16, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return uint16(floatValue), nil
}
// handleUint32
func handleUint32(attribute interface{}) (uint32, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return uint32(floatValue), nil
}
// handleUint64
func handleUint64(attribute interface{}) (uint64, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return uint64(floatValue), nil
}
// handleFloat32
func handleFloat32(attribute interface{}) (float32, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return float32(floatValue), nil
}
// handleFloat64
func handleFloat64(attribute interface{}) (float64, error) {
v := reflect.ValueOf(attribute)
floatValue := v.Interface().(float64)
return float64(floatValue), nil
}
// handleString
func handleString(
attribute interface{},
fieldType reflect.Type,
fieldValue reflect.Value) (value string, err error) {
v := reflect.ValueOf(attribute)
if v.Kind() != reflect.String {
return value, errors.New(fmt.Sprintf("can't unmarshal value of type %s to string", v.Kind().String()))
}
value = v.Interface().(string)
return
}
// handleSlice
func handleSlice(
attribute interface{},
args []string,
fieldType reflect.Type,
fieldValue reflect.Value) (value reflect.Value, err error) {
// check passed values is a struct
submittedValues, ok := attribute.([]interface{})
if !ok {
return reflect.Value{}, errors.New("require slice of values to unmarshall into slice")
}
// find type to pass back to handle field - recursively filling the values
sliceType := fieldType.Elem()
vals := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, len(submittedValues))
for _, val := range submittedValues {
v, tErr := handleField(val, args, sliceType, fieldValue)
if tErr != nil {
return reflect.Value{}, tErr
}
// If this is a slice of slices, just append and move on
// TODO: This only accounts for strings, we need to account for every type in future
if v.Type() == reflect.TypeOf([]string{}) {
vals = reflect.Append(vals, v)
continue
}
if v.Kind() == reflect.Slice {
vals = reflect.Append(vals, v.Elem())
} else {
vals = reflect.Append(vals, v)
}
}
return vals, nil
}
// handleMap
func handleMap(
attribute interface{},
args []string,
fieldType reflect.Type,
) (value reflect.Value, err error) {
// check passed values is a struct
// TODO: Ideally we want to use the actual key type rather than assume string
//t := reflect.TypeOf(attribute).Elem()
//submittedValues := reflect.ValueOf(attribute).Convert(t)
submittedValues, _ := attribute.(map[string]interface{})
vals := reflect.MakeMap(fieldType)
mapIndexType := reflect.TypeOf(vals.Interface()).Key()
mapValueType := reflect.TypeOf(vals.Interface()).Elem()
for key, val := range submittedValues {
var (
v reflect.Value
tErr error
)
isSlice := val != nil && reflect.TypeOf(val).Kind() == reflect.Slice
if isSlice {
v, tErr = handleField(val, args, mapValueType, reflect.New(mapValueType.Elem()))
} else {
v, tErr = handleField(val, args, mapValueType, reflect.New(mapValueType))
}
if tErr != nil {
return reflect.Value{}, tErr
}
converted := reflect.ValueOf(key).Convert(mapIndexType)
if v.Kind() == reflect.Slice {
vals.SetMapIndex(converted, v)
} else {
vals.SetMapIndex(converted, v.Elem())
}
}
return vals, nil
}
// handlePointer
func handlePointer(
attribute interface{},
args []string,
fieldType reflect.Type,
fieldValue reflect.Value) (value reflect.Value, err error) {
t := fieldType.Elem()
value, err = handleField(attribute, args, t, fieldValue)
if err != nil {
return reflect.Value{}, err
}
return
}
func handleTime(attribute interface{}, args []string, fieldValue reflect.Value) (reflect.Value, error) {
var isIso8601 bool
v := reflect.ValueOf(attribute)
if len(args) > 2 {
for _, arg := range args[2:] {
if arg == annotationISO8601 {
isIso8601 = true
}
}
}
if isIso8601 {
var tm string
if v.Kind() == reflect.String {
tm = v.Interface().(string)
} else {
return reflect.ValueOf(time.Now()), ErrInvalidISO8601
}
t, err := time.Parse(iso8601TimeFormat, tm)
if err != nil {
return reflect.ValueOf(time.Now()), ErrInvalidISO8601
}
if fieldValue.Kind() == reflect.Ptr {
return reflect.ValueOf(&t), nil
}
return reflect.ValueOf(t), nil
}
var at int64
if v.Kind() == reflect.Float64 {
at = int64(v.Interface().(float64))
} else if v.Kind() == reflect.Int {
at = v.Int()
} else {
return reflect.ValueOf(time.Now()), ErrInvalidTime
}
t := time.Unix(at, 0)
return reflect.ValueOf(t), nil
}
func handleStruct(
attribute interface{},
fieldValue reflect.Value) (reflect.Value, error) {
data, err := json.Marshal(attribute)
if err != nil {
return reflect.Value{}, err
}
var model reflect.Value
if fieldValue.Kind() == reflect.Ptr {
model = reflect.New(fieldValue.Type().Elem())
} else {
model = reflect.New(fieldValue.Type())
}
// handle custom structs which need UnmarshalJSON to work.
method := model.MethodByName("UnmarshalJSON")
if method.IsValid() {
var buf []byte
if val, ok := attribute.(string); ok {
val = strconv.Quote(val)
buf = []byte(val)
}
if val, ok := attribute.(float64); ok {
buf = []byte(strconv.FormatFloat(val, 'f', -1, 64))
}
if val, ok := attribute.(map[string]interface{}); ok {
buf, _ = json.Marshal(val)
}
in := []reflect.Value{reflect.ValueOf(buf)}
_ = method.Call(in)
return model, nil
}
node := new(ResourceObj)
if err := json.Unmarshal(data, &node.Attributes); err != nil {
return reflect.Value{}, err
}
nulls := make(map[string]interface{})
if err := unmarshalNode(node, nulls, model, nil); err != nil {
return reflect.Value{}, err
}
return model, nil
}
func handleStructSlice(
attribute interface{},
fieldValue reflect.Value) (reflect.Value, error) {
models := reflect.New(fieldValue.Type()).Elem()
dataMap := reflect.ValueOf(attribute).Interface().([]interface{})
if fieldValue.Type().Kind() == reflect.Ptr {
sliceType := reflect.Indirect(fieldValue).Type()
models = reflect.MakeSlice(reflect.SliceOf(sliceType), 0, len(dataMap))
}
for _, data := range dataMap {
model := reflect.New(fieldValue.Type().Elem()).Elem()
value, err := handleStruct(data, model)
if err != nil {
continue
}
models = reflect.Append(models, reflect.Indirect(value))
}
return models, nil
}