-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault.go
More file actions
96 lines (87 loc) · 1.76 KB
/
default.go
File metadata and controls
96 lines (87 loc) · 1.76 KB
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
package greq
import (
"bytes"
"errors"
"fmt"
jsoniter "github.com/json-iterator/go"
"io"
"net/http"
"net/url"
"reflect"
"strings"
)
var (
defClient *Client
buildReqErr = errors.New("build req error")
jsonHeader = http.Header{
"Content-Type": []string{"application/json;charset=utf-8"},
}
formHeader = http.Header{
"Content-Type": []string{"application/x-www-form-urlencoded;charset=utf-8"},
}
)
func getDefaultClient() *Client {
if defClient == nil {
defClient = NewClient(defPoolSize)
}
return defClient
}
func jsonReader(i interface{}) io.Reader {
str, err := jsoniter.Marshal(i)
if err != nil {
return nil
}
return bytes.NewReader(str)
}
func formReader(i interface{}) io.Reader {
if i == nil {
return nil
}
values := url.Values{}
v := reflect.ValueOf(i)
t := v.Type()
switch t.Kind(){
case reflect.Ptr:
v = v.Elem()
fallthrough
case reflect.Map:
iter := v.MapRange()
for iter.Next() {
k := fmt.Sprintf("%v",iter.Key().Interface())
iv := iter.Value()
kind := iv.Kind()
if kind == reflect.Slice || kind == reflect.Array {
for idx := 0 ;idx < iv.Len() ; idx ++ {
currValue := iv.Index(idx).Interface()
values.Add(k,fmt.Sprintf("%v", currValue))
}
} else {
values.Add(
k,
fmt.Sprintf("%v", iter.Value().Interface()),
)
}
}
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
vf := v.Field(i)
name := f.Tag.Get("form")
if len(name) == 0 {
name = f.Name
}
values.Add(name, fmt.Sprintf("%v", vf.Interface()))
}
}
return strings.NewReader(values.Encode())
}
func defReader(i interface{}) io.Reader {
var str string
switch i.(type) {
case string:
str = i.(string)
default:
str = fmt.Sprintf("%v", i)
}
return strings.NewReader(str)
}