forked from huandu/facebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.go
1346 lines (1038 loc) · 33.4 KB
/
result.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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// A facebook graph api client in go.
// https://github.com/huandu/facebook/
//
// Copyright 2012, Huan Du
// Licensed under the MIT license
// https://github.com/huandu/facebook/blob/master/LICENSE
package facebook
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"reflect"
"runtime"
"strconv"
"strings"
)
const (
ERROR_CODE_UNKNOWN = -1 // unknown facebook graph api error code.
debugInfoKey = "__debug__"
debugProtoKey = "__proto__"
debugHeaderKey = "__header__"
usageInfoKey = "__usage__"
facebookAPIVersionHeader = "facebook-api-version"
facebookDebugHeader = "x-fb-debug"
facebookRevHeader = "x-fb-rev"
)
var (
typeOfJSONNumber = reflect.TypeOf(json.Number(""))
typeOfInt = reflect.TypeOf(Int(0))
typeOfInt8 = reflect.TypeOf(Int8(0))
typeOfInt16 = reflect.TypeOf(Int16(0))
typeOfInt32 = reflect.TypeOf(Int32(0))
typeOfInt64 = reflect.TypeOf(Int64(0))
typeOfUint = reflect.TypeOf(Uint(0))
typeOfUint8 = reflect.TypeOf(Uint8(0))
typeOfUint16 = reflect.TypeOf(Uint16(0))
typeOfUint32 = reflect.TypeOf(Uint32(0))
typeOfUint64 = reflect.TypeOf(Uint64(0))
typeOfFloat32 = reflect.TypeOf(Float32(0))
typeOfFloat64 = reflect.TypeOf(Float64(0))
facebookSuccessJSONBytes = []byte("true")
)
// Result is Facebook API call result.
type Result map[string]interface{}
// PagingResult represents facebook API call result with paging information.
type PagingResult struct {
session *Session
paging pagingData
previous string
next string
}
// BatchResult represents facebook batch API call result.
// See https://developers.facebook.com/docs/graph-api/making-multiple-requests/#multiple_methods.
type BatchResult struct {
StatusCode int // HTTP status code.
Header http.Header // HTTP response headers.
Body string // Raw HTTP response body string.
Result Result // Facebook api result parsed from body.
}
// DebugInfo is the debug information returned by facebook when debug mode is enabled.
type DebugInfo struct {
Messages []DebugMessage // debug messages. it can be nil if there is no message.
Header http.Header // all HTTP headers for this response.
Proto string // HTTP protocol name for this response.
// Facebook debug HTTP headers.
FacebookApiVersion string // the actual graph API version provided by facebook-api-version HTTP header.
FacebookDebug string // the X-FB-Debug HTTP header.
FacebookRev string // the x-fb-rev HTTP header.
}
// UsageInfo is the app usage (rate limit) information returned by facebook when rate limits are possible.
type UsageInfo struct {
App struct {
CallCount int `json:"call_count"`
TotalTime int `json:"total_time"`
TotalCPUTime int `json:"total_cputime"`
} `json:"app"`
Page struct {
CallCount int `json:"call_count"`
TotalTime int `json:"total_time"`
TotalCPUTime int `json:"total_cputime"`
} `json:"page"`
}
// DebugMessage is one debug message in "__debug__" of graph API response.
type DebugMessage struct {
Type string
Message string
Link string
}
// Special number types which can be decoded from either a number or a string.
// If developers intend to use a string in JSON as a number, these types can parse
// string to a number implicitly in `Result#Decode` or `Result#DecodeField`.
//
// Caveats: Parsing a string to a number may lose accuracy or shadow some errors.
type (
Int int
Int8 int8
Int16 int16
Int32 int32
Int64 int64
Uint uint
Uint8 uint8
Uint16 uint16
Uint32 uint32
Uint64 uint64
Float32 float32
Float64 float64
)
// MakeResult makes a Result from facebook Graph API response.
func MakeResult(jsonBytes []byte) (Result, error) {
res := Result{}
err := makeResult(jsonBytes, &res)
if err != nil {
return nil, err
}
// facebook may return an error
return res, res.Err()
}
func makeResult(jsonBytes []byte, res interface{}) error {
if bytes.Equal(jsonBytes, facebookSuccessJSONBytes) {
return nil
}
jsonReader := bytes.NewReader(jsonBytes)
dec := json.NewDecoder(jsonReader)
// issue #19
// app_scoped user_id in a post-Facebook graph 2.0 would exceeds 2^53.
// use Number instead of float64 to avoid precision lost.
dec.UseNumber()
err := dec.Decode(res)
if err != nil {
typ := reflect.TypeOf(res)
if typ != nil {
// if res is a slice, jsonBytes may be a facebook error.
// try to decode it as Error.
kind := typ.Kind()
if kind == reflect.Ptr {
typ = typ.Elem()
kind = typ.Kind()
}
if kind == reflect.Array || kind == reflect.Slice {
var errRes Result
err = makeResult(jsonBytes, &errRes)
if err != nil {
return err
}
err = errRes.Err()
if err == nil {
err = fmt.Errorf("cannot format facebook response; expect an array but get an object")
}
return err
}
}
return fmt.Errorf("cannot format facebook response. %v", err)
}
return nil
}
// Get gets a field from Result.
//
// Field can be a dot separated string.
// If field name is "a.b.c", it will try to return value of res["a"]["b"]["c"].
//
// To access array items, use index value in field.
// For instance, field "a.0.c" means to read res["a"][0]["c"].
//
// It doesn't work with Result which has a key contains dot. Use GetField in this case.
//
// Returns nil if field doesn't exist.
func (res Result) Get(field string) interface{} {
if field == "" {
return res
}
f := strings.Split(field, ".")
return res.get(f)
}
// GetField gets a field from Result.
//
// Arguments are treated as keys to access value in Result.
// If arguments are "a","b","c", it will try to return value of res["a"]["b"]["c"].
//
// To access array items, use index value as a string.
// For instance, args of "a", "0", "c" means to read res["a"][0]["c"].
//
// Returns nil if field doesn't exist.
func (res Result) GetField(fields ...string) interface{} {
if len(fields) == 0 {
return res
}
return res.get(fields)
}
func (res Result) get(fields []string) interface{} {
v, ok := res[fields[0]]
if !ok || v == nil {
return nil
}
if len(fields) == 1 {
return v
}
value := getValueField(reflect.ValueOf(v), fields[1:])
if !value.IsValid() {
return nil
}
return value.Interface()
}
func getValueField(value reflect.Value, fields []string) reflect.Value {
valueType := value.Type()
kind := valueType.Kind()
field := fields[0]
switch kind {
case reflect.Array, reflect.Slice:
// field must be a number.
n, err := strconv.ParseUint(field, 10, 0)
if err != nil {
return reflect.Value{}
}
if n >= uint64(value.Len()) {
return reflect.Value{}
}
// work around a reflect package pitfall.
value = reflect.ValueOf(value.Index(int(n)).Interface())
case reflect.Map:
v := value.MapIndex(reflect.ValueOf(field))
if !v.IsValid() {
return v
}
// get real value type.
value = reflect.ValueOf(v.Interface())
default:
return reflect.Value{}
}
if len(fields) == 1 {
return value
}
return getValueField(value, fields[1:])
}
// Decode decodes full result to a struct.
// It only decodes fields defined in the struct.
//
// As all facebook response fields are lower case strings,
// Decode will convert all camel-case field names to lower case string.
// e.g. field name "FooBar" will be converted to "foo_bar".
// The side effect is that if a struct has 2 fields with only capital
// differences, decoder will map these fields to a same result value.
//
// If a field is missing in the result, Decode keeps it unchanged by default.
//
// The decoding of each struct field can be customized by the format string stored
// under the "facebook" key or the "json" key in the struct field's tag.
// The "facebook" key is recommended as it's specifically designed for this package.
//
// Examples:
//
// type Foo struct {
// // "id" must exist in response. note the leading comma.
// Id string `facebook:",required"`
//
// // use "name" as field name in response.
// TheName string `facebook:"name"`
//
// // the "json" key also works as expected.
// Key string `json:"my_key"`
//
// // if both "facebook" and "json" key are set, the "facebook" key is used.
// Value string `facebook:"value" json:"shadowed"`
// }
//
// To change default behavior, set a struct tag `facebook:",required"` to fields
// should not be missing.
//
// Returns error if v is not a struct or any required v field name absents in res.
func (res Result) Decode(v interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
if errStr, ok := r.(string); ok {
err = errors.New(errStr)
return
}
if errErr, ok := r.(error); ok {
err = errErr
return
}
panic(r)
}
}()
err = res.decode(reflect.ValueOf(v), "")
return
}
// DecodeField decodes a field of result to any type, including struct.
// Field name format is defined in Result.Get().
//
// More details about decoding struct see Result.Decode().
func (res Result) DecodeField(field string, v interface{}) error {
f := res.Get(field)
if f == nil {
return fmt.Errorf("field '%v' doesn't exist in result", field)
}
return decodeField(reflect.ValueOf(f), reflect.ValueOf(v), field)
}
// Err returns an error if Result is a Graph API error.
//
// The returned error can be converted to Error by type assertion.
// err := res.Err()
// if err != nil {
// if e, ok := err.(*Error); ok {
// // read more details in e.Message, e.Code and e.Type
// }
// }
//
// For more information about Graph API Errors, see
// https://developers.facebook.com/docs/reference/api/errors/
func (res Result) Err() error {
var err Error
e := res.DecodeField("error", &err)
// no "error" in result. result is not an error.
if e != nil {
return nil
}
// code may be missing in error.
// assign a non-zero value to it.
if err.Code == 0 {
err.Code = ERROR_CODE_UNKNOWN
}
return &err
}
// Paging creates a PagingResult for this Result and
// returns error if the Result cannot be used for paging.
//
// Facebook uses following JSON structure to response paging information.
// If "data" doesn't present in Result, Paging will return error.
// {
// "data": [...],
// "paging": {
// "previous": "https://graph.facebook.com/...",
// "next": "https://graph.facebook.com/..."
// }
// }
func (res Result) Paging(session *Session) (*PagingResult, error) {
return newPagingResult(session, res)
}
// Batch creates a BatchResult for this result and
// returns error if the Result is not a batch api response.
//
// See BatchApi document for a sample usage.
func (res Result) Batch() (*BatchResult, error) {
return newBatchResult(res)
}
// DebugInfo creates a DebugInfo for this result if this result
// has "__debug__" key.
func (res Result) DebugInfo() *DebugInfo {
var info Result
err := res.DecodeField(debugInfoKey, &info)
if err != nil {
return nil
}
debugInfo := &DebugInfo{}
info.DecodeField("messages", &debugInfo.Messages)
if proto, ok := info[debugProtoKey]; ok {
if v, ok := proto.(string); ok {
debugInfo.Proto = v
}
}
if header, ok := info[debugHeaderKey]; ok {
if v, ok := header.(http.Header); ok {
debugInfo.Header = v
debugInfo.FacebookApiVersion = v.Get(facebookAPIVersionHeader)
debugInfo.FacebookDebug = v.Get(facebookDebugHeader)
debugInfo.FacebookRev = v.Get(facebookRevHeader)
}
}
return debugInfo
}
// UsageInfo returns app and page usage info (rate limits)
func (res Result) UsageInfo() *UsageInfo {
if usageInfo, ok := res[usageInfoKey]; ok {
if usage, ok := usageInfo.(*UsageInfo); ok {
return usage
}
}
return nil
}
func (res Result) decode(v reflect.Value, fullName string) error {
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return fmt.Errorf("output value must be a struct")
}
if !v.CanSet() {
return fmt.Errorf("output value cannot be set")
}
var field reflect.Value
var fieldInfo reflect.StructField
var name, dot string
var val interface{}
var ok, required bool
var err error
if fullName != "" {
dot = "."
}
vType := v.Type()
num := vType.NumField()
for i := 0; i < num; i++ {
name = ""
required = false
field = v.Field(i)
fieldInfo = vType.Field(i)
// parse struct field tag.
if fbTag := fieldInfo.Tag.Get("facebook"); fbTag != "" {
if fbTag == "-" {
continue
}
index := strings.IndexRune(fbTag, ',')
if index == -1 {
name = fbTag
} else {
name = fbTag[:index]
if fbTag[index:] == ",required" {
required = true
}
}
} else {
// compatible with json tag.
fbTag = fieldInfo.Tag.Get("json")
if fbTag == "-" {
continue
}
index := strings.IndexRune(fbTag, ',')
if index == -1 {
name = fbTag
} else {
name = fbTag[:index]
}
}
// embedded field is "expanded" when decoding.
// special case: treat it as a normal field if the name is not empty.
if fieldInfo.Anonymous && name == "" {
if err = decodeField(reflect.ValueOf(res), field, fullName); err != nil {
return err
}
continue
}
if name == "" {
name = camelCaseToUnderScore(fieldInfo.Name)
}
val, ok = res[name]
if !ok {
// check whether the field is required. if so, report error.
if required {
return fmt.Errorf("cannot find field '%v%v%v' in result", fullName, dot, name)
}
continue
}
if err = decodeField(reflect.ValueOf(val), field, fmt.Sprintf("%v%v%v", fullName, dot, name)); err != nil {
return err
}
}
return nil
}
func decodeField(val reflect.Value, field reflect.Value, fullName string) error {
if field.Kind() == reflect.Ptr {
// reset Ptr field if val is nil.
if !val.IsValid() {
if !field.IsNil() && field.CanSet() {
field.Set(reflect.Zero(field.Type()))
}
return nil
}
if field.IsNil() {
field.Set(reflect.New(field.Type().Elem()))
}
field = field.Elem()
}
if !field.CanSet() {
return fmt.Errorf("field '%v' cannot be decoded; make sure the output value is able to be set", fullName)
}
if !val.IsValid() {
return fmt.Errorf("field '%v' is not a pointer; fail to assign nil to it", fullName)
}
// if field implements Unmarshaler, let field unmarshals data itself.
if unmarshaler := indirect(field); unmarshaler != nil {
data, err := json.Marshal(val.Interface())
if err != nil {
return fmt.Errorf("fail to marshal value for field '%v' with error %v", fullName, err)
}
return unmarshaler.UnmarshalJSON(data)
}
kind := field.Kind()
fieldType := field.Type()
valType := val.Type()
switch kind {
case reflect.Bool:
if valType.Kind() == reflect.Bool {
field.SetBool(val.Bool())
} else {
return fmt.Errorf("field '%v' is not a bool in result", fullName)
}
case reflect.Int8:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < math.MinInt8 || n > math.MaxInt64 {
return fmt.Errorf("field '%v' value exceeds the range of int8", fullName)
}
field.SetInt(int64(n))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > math.MaxInt8 {
return fmt.Errorf("field '%v' value exceeds the range of int8", fullName)
}
field.SetInt(int64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < math.MinInt8 || n > math.MaxInt8 {
return fmt.Errorf("field '%v' value exceeds the range of int8", fullName)
}
field.SetInt(int64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Int8.
if val.Type() != typeOfJSONNumber && fieldType != typeOfInt8 {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseInt(val.String(), 10, 8)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid int8", fullName)
}
field.SetInt(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Int16:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < math.MinInt16 || n > math.MaxInt16 {
return fmt.Errorf("field '%v' value exceeds the range of int16", fullName)
}
field.SetInt(int64(n))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > math.MaxInt16 {
return fmt.Errorf("field '%v' value exceeds the range of int16", fullName)
}
field.SetInt(int64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < math.MinInt16 || n > math.MaxInt16 {
return fmt.Errorf("field '%v' value exceeds the range of int16", fullName)
}
field.SetInt(int64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Int16.
if val.Type() != typeOfJSONNumber && fieldType != typeOfInt16 {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseInt(val.String(), 10, 16)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid int16", fullName)
}
field.SetInt(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Int32:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < math.MinInt32 || n > math.MaxInt32 {
return fmt.Errorf("field '%v' value exceeds the range of int32", fullName)
}
field.SetInt(int64(n))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > math.MaxInt32 {
return fmt.Errorf("field '%v' value exceeds the range of int32", fullName)
}
field.SetInt(int64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < math.MinInt32 || n > math.MaxInt32 {
return fmt.Errorf("field '%v' value exceeds the range of int32", fullName)
}
field.SetInt(int64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Int32.
if val.Type() != typeOfJSONNumber && fieldType != typeOfInt32 {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseInt(val.String(), 10, 32)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid int32", fullName)
}
field.SetInt(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Int64:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
field.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > math.MaxInt64 {
return fmt.Errorf("field '%v' value exceeds the range of int64", fullName)
}
field.SetInt(int64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < math.MinInt64 || n > math.MaxInt64 {
return fmt.Errorf("field '%v' value exceeds the range of int64", fullName)
}
field.SetInt(int64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Int64.
if val.Type() != typeOfJSONNumber && fieldType != typeOfInt64 {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseInt(val.String(), 10, 64)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid int64", fullName)
}
field.SetInt(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Int:
bits := field.Type().Bits()
var min, max int64
if bits == 32 {
min = math.MinInt32
max = math.MaxInt32
} else if bits == 64 {
min = math.MinInt64
max = math.MaxInt64
}
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < min || n > max {
return fmt.Errorf("field '%v' value exceeds the range of int", fullName)
}
field.SetInt(int64(n))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > uint64(max) {
return fmt.Errorf("field '%v' value exceeds the range of int", fullName)
}
field.SetInt(int64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < float64(min) || n > float64(max) {
return fmt.Errorf("field '%v' value exceeds the range of int", fullName)
}
field.SetInt(int64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Int.
if val.Type() != typeOfJSONNumber && fieldType != typeOfInt {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseInt(val.String(), 10, bits)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid int%v", fullName, bits)
}
field.SetInt(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Uint8:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < 0 || n > math.MaxUint8 {
return fmt.Errorf("field '%v' value exceeds the range of uint8", fullName)
}
field.SetUint(uint64(n))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > math.MaxUint8 {
return fmt.Errorf("field '%v' value exceeds the range of uint8", fullName)
}
field.SetUint(uint64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < 0 || n > math.MaxUint8 {
return fmt.Errorf("field '%v' value exceeds the range of uint8", fullName)
}
field.SetUint(uint64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Uint8.
if val.Type() != typeOfJSONNumber && fieldType != typeOfUint8 {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseUint(val.String(), 10, 8)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid uint8", fullName)
}
field.SetUint(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Uint16:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < 0 || n > math.MaxUint16 {
return fmt.Errorf("field '%v' value exceeds the range of uint16", fullName)
}
field.SetUint(uint64(n))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > math.MaxUint16 {
return fmt.Errorf("field '%v' value exceeds the range of uint16", fullName)
}
field.SetUint(uint64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < 0 || n > math.MaxUint16 {
return fmt.Errorf("field '%v' value exceeds the range of uint16", fullName)
}
field.SetUint(uint64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Uint16.
if val.Type() != typeOfJSONNumber && fieldType != typeOfUint16 {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseUint(val.String(), 10, 16)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid uint16", fullName)
}
field.SetUint(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Uint32:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < 0 || n > math.MaxUint32 {
return fmt.Errorf("field '%v' value exceeds the range of uint32", fullName)
}
field.SetUint(uint64(n))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := val.Uint()
if n > math.MaxUint32 {
return fmt.Errorf("field '%v' value exceeds the range of uint32", fullName)
}
field.SetUint(uint64(n))
case reflect.Float32, reflect.Float64:
n := val.Float()
if n < 0 || n > math.MaxUint32 {
return fmt.Errorf("field '%v' value exceeds the range of uint32", fullName)
}
field.SetUint(uint64(n))
case reflect.String:
// val is allowed to be used as number only if val is json.Number or field is fb.Uint32.
if val.Type() != typeOfJSONNumber && fieldType != typeOfUint32 {
return fmt.Errorf("field '%v' value is string, not a number", fullName)
}
n, err := strconv.ParseUint(val.String(), 10, 32)
if err != nil {
return fmt.Errorf("field '%v' value is not a valid uint32", fullName)
}
field.SetUint(n)
default:
return fmt.Errorf("field '%v' is not an integer in result", fullName)
}
case reflect.Uint64:
switch valType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := val.Int()
if n < 0 {