-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
107 lines (102 loc) · 2.42 KB
/
query.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
package requests
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/url"
"reflect"
"strings"
)
func (c *Client) getJsonByte(v interface{}) []byte {
jsonData, err := json.Marshal(v)
if err != nil {
log.Printf("json.Marshal error: %v", err)
return nil
}
return jsonData
}
func (c *Client) JsonQuery(data interface{}) *Client {
c.Header("Content-Type", ContentTypeJson)
switch dataAny := data.(type) {
case url.Values:
result := make(map[string]string)
for key, val := range dataAny {
if len(val) > 0 {
result[key] = val[0]
}
}
c.jsonData = c.getJsonByte(result)
case map[string]interface{}, []map[string]string, []map[string]int:
c.jsonData = c.getJsonByte(dataAny)
case string:
if dataAny[:1] == "{" && dataAny[len(dataAny)-1:] == "}" {
c.jsonData = []byte(dataAny)
}
default:
if reflect.ValueOf(data).Kind() == reflect.Struct {
c.jsonData = c.getJsonByte(data)
}
}
return c
}
func (c *Client) FormQuery(data interface{}) *Client {
c.Header("Content-Type", ContentTypeForm)
switch dataAny := data.(type) {
case url.Values:
for k, v := range dataAny {
c.dataForm.Set(k, v[0])
}
case map[string]interface{}:
for k, v := range dataAny {
c.dataForm.Set(k, fmt.Sprintf("%v", v))
}
case map[string]string:
for k, v := range dataAny {
c.dataForm.Set(k, v)
}
case string:
dataForm, err := url.ParseQuery(dataAny)
if err != nil {
log.Printf("url.ParseQuery error: %v", err)
} else {
for k, v := range dataForm {
c.dataForm.Set(k, v[0])
}
}
}
return c
}
func (c *Client) QueryResult() io.Reader {
if c.jsonData != nil {
return bytes.NewReader(c.jsonData)
} else if c.dataForm != nil {
return bytes.NewReader([]byte(c.dataForm.Encode()))
} else {
return nil
}
}
func (c *Client) Query(data interface{}, queryType string) *Client {
if queryType == ContentTypeFormString {
c.FormQuery(data)
} else if queryType == ContentTypeJsonString {
c.JsonQuery(data)
} else {
log.Printf("query error: form and json is false")
}
return c
}
func (c *Client) QueryFunc(f func(c *Client) (interface{}, string)) *Client {
data, queryType := f(c)
if data != nil {
if !strings.Contains(queryType, strings.Join([]string{ContentTypeJsonString, ContentTypeFormString}, "|")) {
log.Printf("queryType error: %s is not support", queryType)
} else {
c.Query(data, queryType)
}
} else {
log.Printf("QueryFunc error: %s", "QueryFunc return nil")
}
return c
}