forked from huandu/facebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.go
744 lines (599 loc) · 19.3 KB
/
misc.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
// 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"
"fmt"
"io"
"mime/multipart"
"net/url"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"unicode"
)
// Gets a field.
//
// Field can be a dot separated string.
// It means, if field name is "a.b.c", gets field value 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"].
//
// 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)
}
func (res Result) get(fields []string) interface{} {
var arr []interface{}
v, ok := res[fields[0]]
if !ok || v == nil {
return nil
}
if len(fields) == 1 {
return v
}
for arr, ok = v.([]interface{}); ok; arr, ok = v.([]interface{}) {
fields = fields[1:]
n, err := strconv.ParseUint(fields[0], 10, 0)
if err != nil {
return nil
}
if n >= uint64(len(arr)) {
return nil
}
v = arr[n]
if len(fields) == 1 {
return v
}
}
res, ok = v.(map[string]interface{})
if !ok {
return nil
}
return Result(res).get(fields[1:])
}
// 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.
//
// Decode can read struct field tag value to change default behavior.
//
// 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"`
// }
//
// 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)
}
err = r.(error)
}
}()
err = res.decode(reflect.ValueOf(v), "")
return
}
// 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(f, reflect.ValueOf(v), field)
}
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.")
}
if fullName != "" {
fullName += "."
}
var field reflect.Value
var name, fbTag string
var val interface{}
var ok, required bool
var err error
vType := v.Type()
num := vType.NumField()
for i := 0; i < num; i++ {
name = ""
required = false
field = v.Field(i)
fbTag = vType.Field(i).Tag.Get("facebook")
// parse struct field tag
if fbTag != "" {
index := strings.IndexRune(fbTag, ',')
if index == -1 {
name = fbTag
} else {
name = fbTag[:index]
if fbTag[index:] == ",required" {
required = true
}
}
}
if name == "" {
name = camelCaseToUnderScore(v.Type().Field(i).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' in result.", fullName, name)
}
continue
}
if err = decodeField(val, field, fmt.Sprintf("%v%v", fullName, name)); err != nil {
return err
}
}
return nil
}
// Checks if Result is a Graph API error.
// Returns nil if Result is not an 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
}
func decodeField(val interface{}, field reflect.Value, fullName string) error {
if field.Kind() == reflect.Ptr {
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)
}
kind := field.Kind()
switch kind {
case reflect.Bool:
if b, ok := val.(bool); ok {
field.SetBool(b)
} else {
return fmt.Errorf("field '%v' is not a bool in result.", fullName)
}
case reflect.Int8:
if n, ok := val.(float64); ok {
if n < -128 || n > 127 {
return fmt.Errorf("field '%v' value exceeds the range of int8.", fullName)
}
field.SetInt(int64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Int16:
if n, ok := val.(float64); ok {
if n < -32768 || n > 32767 {
return fmt.Errorf("field '%v' value exceeds the range of int16.", fullName)
}
field.SetInt(int64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Int32:
if n, ok := val.(float64); ok {
if n < -2147483648 || n > 2147483647 {
return fmt.Errorf("field '%v' value exceeds the range of int32.", fullName)
}
field.SetInt(int64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Int64:
if n, ok := val.(float64); ok {
if n < -9223372036854775808 || n > 9223372036854775807 {
return fmt.Errorf("field '%v' value exceeds the range of int64.", fullName)
}
field.SetInt(int64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Int:
if n, ok := val.(float64); ok {
if n < -9223372036854775808 || n > 9223372036854775807 {
return fmt.Errorf("field '%v' value exceeds the range of int.", fullName)
}
field.SetInt(int64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Uint8:
if n, ok := val.(float64); ok {
if n < 0 || n > 0xFF {
return fmt.Errorf("field '%v' value exceeds the range of uint8.", fullName)
}
field.SetUint(uint64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Uint16:
if n, ok := val.(float64); ok {
if n < 0 || n > 0xFFFF {
return fmt.Errorf("field '%v' value exceeds the range of uint16.", fullName)
}
field.SetUint(uint64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Uint32:
if n, ok := val.(float64); ok {
if n < 0 || n > 0xFFFFFFFF {
return fmt.Errorf("field '%v' value exceeds the range of uint32.", fullName)
}
field.SetUint(uint64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Uint64:
if n, ok := val.(float64); ok {
if n < 0 || n > 0xFFFFFFFFFFFFFFFF {
return fmt.Errorf("field '%v' value exceeds the range of uint64.", fullName)
}
field.SetUint(uint64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Uint:
if n, ok := val.(float64); ok {
if n < 0 || n > 0xFFFFFFFFFFFFFFFF {
return fmt.Errorf("field '%v' value exceeds the range of uint.", fullName)
}
field.SetUint(uint64(n))
} else {
return fmt.Errorf("field '%v' is not an integer in result.", fullName)
}
case reflect.Float32, reflect.Float64:
if f, ok := val.(float64); ok {
field.SetFloat(f)
} else {
return fmt.Errorf("field '%v' is not a float in result.", fullName)
}
case reflect.String:
if s, ok := val.(string); ok {
field.SetString(s)
} else {
return fmt.Errorf("field '%v' is not a string in result.", fullName)
}
case reflect.Struct:
if r, ok := val.(map[string]interface{}); ok {
if err := Result(r).decode(field, fullName); err != nil {
return err
}
} else {
return fmt.Errorf("field '%v' is not a json object in result.", fullName)
}
case reflect.Map:
if m, ok := val.(map[string]interface{}); ok {
// map key must be string
if field.Type().Key().Kind() != reflect.String {
return fmt.Errorf("field '%v' in struct is a map with non-string key type. it's not allowed.", fullName)
}
var needAddr bool
valueType := field.Type().Elem()
// shortcut for map of interface
if valueType.Kind() == reflect.Interface {
field.Set(reflect.ValueOf(m))
break
}
if field.IsNil() {
field.Set(reflect.MakeMap(field.Type()))
}
if valueType.Kind() == reflect.Ptr {
valueType = valueType.Elem()
needAddr = true
}
for key, value := range m {
v := reflect.New(valueType)
if err := decodeField(value, v, fmt.Sprintf("%v.%v", fullName, key)); err != nil {
return err
}
if needAddr {
field.SetMapIndex(reflect.ValueOf(key), v)
} else {
field.SetMapIndex(reflect.ValueOf(key), v.Elem())
}
}
} else {
return fmt.Errorf("field '%v' is not a json object in result.", fullName)
}
case reflect.Slice, reflect.Array:
if a, ok := val.([]interface{}); ok {
if kind == reflect.Array {
if field.Len() < len(a) {
return fmt.Errorf("cannot copy all field '%v' values to struct. expected len is %v. actual len is %v.",
fullName, field.Len(), len(a))
}
}
var slc reflect.Value
var needAddr bool
valueType := field.Type().Elem()
// shortcut for array of interface
if valueType.Kind() == reflect.Interface {
if kind == reflect.Array {
for i := 0; i < len(a); i++ {
field.Index(i).Set(reflect.ValueOf(a[i]))
}
} else { // kind is slice
field.Set(reflect.ValueOf(a))
}
break
}
if kind == reflect.Array {
slc = field.Slice(0, len(a))
} else { // kind is slice
slc = reflect.MakeSlice(field.Type(), len(a), len(a))
field.Set(slc)
}
if valueType.Kind() == reflect.Ptr {
needAddr = true
valueType = valueType.Elem()
}
for i := 0; i < len(a); i++ {
v := reflect.New(valueType)
if err := decodeField(a[i], v, fmt.Sprintf("%v.%v", fullName, i)); err != nil {
return err
}
if needAddr {
slc.Index(i).Set(v)
} else {
slc.Index(i).Set(v.Elem())
}
}
} else {
return fmt.Errorf("field '%v' is not a json array in result.", fullName)
}
default:
return fmt.Errorf("field '%v' in struct uses unsupported type '%v'.", fullName, kind)
}
return nil
}
// Makes a new Params instance by given data.
// Data must be a struct or a map with string keys.
// MakeParams will change all struct field name to lower case name with underscore.
// e.g. "FooBar" will be changed to "foo_bar".
//
// Returns nil if data cannot be used to make a Params instance.
func MakeParams(data interface{}) (params Params) {
if p, ok := data.(Params); ok {
return p
}
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
params = nil
}
}()
params = makeParams(reflect.ValueOf(data))
return
}
func makeParams(value reflect.Value) (params Params) {
for value.Kind() == reflect.Ptr || value.Kind() == reflect.Interface {
value = value.Elem()
}
// only map with string keys can be converted to Params
if value.Kind() == reflect.Map && value.Type().Key().Kind() == reflect.String {
params = Params{}
for _, key := range value.MapKeys() {
params[key.String()] = value.MapIndex(key).Interface()
}
return
}
if value.Kind() != reflect.Struct {
return
}
params = Params{}
num := value.NumField()
for i := 0; i < num; i++ {
name := camelCaseToUnderScore(value.Type().Field(i).Name)
field := value.Field(i)
for field.Kind() == reflect.Ptr {
field = field.Elem()
}
switch field.Kind() {
case reflect.Chan, reflect.Func, reflect.UnsafePointer, reflect.Invalid:
// these types won't be marshalled in json.
params = nil
return
default:
params[name] = field.Interface()
}
}
return
}
// Encodes params to query string.
// If map value is not a string, Encode uses json.Marshal() to convert value to string.
//
// Encode will panic if Params contains values that cannot be marshalled to json string.
func (params Params) Encode(writer io.Writer) (mime string, err error) {
if params == nil || len(params) == 0 {
mime = _MIME_FORM_URLENCODED
return
}
// check whether params contains any binary data.
hasBinary := false
for _, v := range params {
typ := reflect.TypeOf(v)
if typ == typeOfPointerToBinaryData || typ == typeOfPointerToBinaryFile {
hasBinary = true
break
}
}
if hasBinary {
return params.encodeMultipartForm(writer)
}
return params.encodeFormUrlEncoded(writer)
}
func (params Params) encodeFormUrlEncoded(writer io.Writer) (mime string, err error) {
var jsonStr []byte
written := false
for k, v := range params {
if written {
io.WriteString(writer, "&")
}
io.WriteString(writer, url.QueryEscape(k))
io.WriteString(writer, "=")
if reflect.TypeOf(v).Kind() == reflect.String {
io.WriteString(writer, url.QueryEscape(reflect.ValueOf(v).String()))
} else {
jsonStr, err = json.Marshal(v)
if err != nil {
return
}
io.WriteString(writer, url.QueryEscape(string(jsonStr)))
}
written = true
}
mime = _MIME_FORM_URLENCODED
return
}
func (params Params) encodeMultipartForm(writer io.Writer) (mime string, err error) {
w := multipart.NewWriter(writer)
defer func() {
w.Close()
mime = w.FormDataContentType()
}()
for k, v := range params {
switch value := v.(type) {
case *BinaryData:
var dst io.Writer
dst, err = w.CreateFormFile(k, value.Filename)
if err != nil {
return
}
_, err = io.Copy(dst, value.Source)
if err != nil {
return
}
case *BinaryFile:
var dst io.Writer
var file *os.File
dst, err = w.CreateFormFile(k, value.Filename)
if err != nil {
return
}
file, err = os.Open(value.Path)
if err != nil {
return
}
_, err = io.Copy(dst, file)
if err != nil {
return
}
default:
var dst io.Writer
var jsonStr []byte
dst, err = w.CreateFormField(k)
if reflect.TypeOf(v).Kind() == reflect.String {
io.WriteString(dst, reflect.ValueOf(v).String())
} else {
jsonStr, err = json.Marshal(v)
if err != nil {
return
}
_, err = dst.Write(jsonStr)
if err != nil {
return
}
}
}
}
return
}
func camelCaseToUnderScore(name string) string {
if name == "" {
return ""
}
buf := &bytes.Buffer{}
for _, r := range name {
if unicode.IsUpper(r) {
if buf.Len() != 0 {
buf.WriteRune('_')
}
buf.WriteRune(unicode.ToLower(r))
} else {
buf.WriteRune(r)
}
}
return buf.String()
}
// Returns error string.
func (e *Error) Error() string {
return e.Message
}
// Creates a new binary data holder.
func Data(filename string, source io.Reader) *BinaryData {
return &BinaryData{
Filename: filename,
Source: source,
}
}
// Creates a binary file holder.
func File(filename, path string) *BinaryFile {
return &BinaryFile{
Filename: filename,
Path: path,
}
}