-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.go
287 lines (252 loc) · 5.99 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
package util
import (
"context"
"encoding/json"
"errors"
"fmt"
"mime/multipart"
"net/http"
"reflect"
"strconv"
"strings"
"unsafe"
"github.com/gorilla/mux"
"github.com/mitchellh/mapstructure"
)
func GetClientKey(req *http.Request) string {
deviceID := req.Header.Get("X-Device-ID")
if deviceID != "" {
return MD5(deviceID)
}
real := req.Header.Get("X-Real-IP")
if real == "" {
real = req.RemoteAddr
}
return MD5(real + req.UserAgent())
}
func IsLogin(req *http.Request) bool {
isLoginStr := req.Header.Get("isLogin")
isLogin, err := strconv.ParseBool(isLoginStr)
if err != nil {
return false
}
return isLogin
}
func DecodeTokenByKey(req *http.Request, key string) map[string]interface{} {
token := req.Header.Get(key)
if token == "" {
return nil
}
return DecodeToken(token)
}
func DecodeToken(token string) map[string]interface{} {
mapSerialize, err := DecodeMap(token)
if err != nil {
return nil
}
return *mapSerialize
}
func ParserDataRequest(req *http.Request, data interface{}) error {
kindOfJ := reflect.ValueOf(data).Kind()
if kindOfJ != reflect.Ptr {
return errors.New("data is not pointer")
}
switch req.Header.Get("Content-Type") {
case "application/json":
err := json.NewDecoder(req.Body).Decode(data)
if err != nil {
return err
}
case "application/x-www-form-urlencoded":
rt := reflect.TypeOf(data).Elem()
keys := []string{}
for i := 0; i < rt.NumField(); i++ {
if key, ok := rt.Field(i).Tag.Lookup("json"); ok {
keys = append(keys, key)
} else {
keys = append(keys, strings.ToLower(rt.Field(i).Name))
}
}
vars, err := GetPostValue(req, false, keys)
if err != nil {
return err
}
decoderConf := &mapstructure.DecoderConfig{
TagName: "json",
Metadata: nil,
Result: data}
decoder, err := mapstructure.NewDecoder(decoderConf)
if err != nil {
return err
}
err = decoder.Decode(vars)
if err != nil {
return err
}
}
return nil
}
func GetQueryValue(req *http.Request, keys []string, defaultEmpty bool) map[string]interface{} {
queries := req.URL.Query()
result := make(map[string]interface{})
for _, key := range keys {
value, ok := queries[key]
if !ok {
// if key not exist. use empty string
if defaultEmpty {
result[key] = ""
}
continue
}
if len(value) == 1 {
result[key] = value[0]
} else {
result[key] = value
}
}
return result
}
func GetPostValue(req *http.Request, defaultEmpty bool, keys []string) (map[string]interface{}, error) {
err := req.ParseForm()
if err != nil {
return nil, err
}
result := make(map[string]interface{})
for _, key := range keys {
if vs := req.PostForm[key]; len(vs) > 0 {
result[key] = vs[0]
} else if defaultEmpty {
result[key] = ""
}
}
return result, nil
}
type RequestFile struct {
ReqFile multipart.File
ReqHeader *multipart.FileHeader
}
func GetMutiFormPostValue(req *http.Request, fileKeys []string, valueKeys []string) (map[string]RequestFile, map[string]interface{}, error) {
req.ParseMultipartForm(32 << 20)
fileMap := make(map[string]RequestFile)
for _, fk := range fileKeys {
file, handler, err := req.FormFile(fk)
if err != nil {
for _, value := range fileMap {
defer value.ReqFile.Close()
}
return nil, nil, err
}
fileMap[fk] = RequestFile{file, handler}
}
valueMap := make(map[string]interface{})
for _, vk := range valueKeys {
valueMap[vk] = req.FormValue(vk)
}
return fileMap, valueMap, nil
}
func GetPathVars(req *http.Request, keys []string) map[string]interface{} {
vars := mux.Vars(req)
if len(vars) == 0 {
return nil
}
valueMap := make(map[string]interface{})
for _, key := range keys {
if v, ok := vars[key]; ok {
valueMap[key] = v
} else {
valueMap[key] = ""
}
}
if len(valueMap) == 0 {
return nil
}
return valueMap
}
type CtxKey string
func GetCtxVal(req *http.Request, ck CtxKey) interface{} {
ctx := req.Context()
return ctx.Value(ck)
}
func SetCtxKeyVal(r *http.Request, ck CtxKey, val interface{}) *http.Request {
ctx := context.WithValue(r.Context(), ck, val)
return r.WithContext(ctx)
}
func GetFullUrlStr(req *http.Request) string {
prot := "http"
if req.TLS != nil {
prot = "https"
}
return fmt.Sprintf("%s://%s%s", prot, req.Host, req.RequestURI)
}
func GetClientInfo(req *http.Request) map[string]interface{} {
result := map[string]interface{}{
"UserAgent": req.UserAgent(),
}
return result
}
//ReturnExist will return new if new is not empty else return original
func ReturnExist(ori interface{}, new interface{}) interface{} {
switch dtype := reflect.TypeOf(ori).Kind(); dtype {
case reflect.Int:
if new.(int) == 0 {
return ori
}
return new
case reflect.Int64:
if new.(int64) == 0 {
return ori
}
return new
case reflect.String:
if new.(string) == "" {
return ori
}
return new
case reflect.Array:
if reflect.ValueOf(new).Len() == 0 {
return ori
}
return new
case reflect.Slice:
if reflect.ValueOf(new).Len() == 0 {
return ori
}
return new
case reflect.Struct:
f := reflect.New(reflect.TypeOf(ori)).Elem().Interface()
if f == new {
return ori
}
return new
}
return nil
}
func GetHost(req *http.Request) string {
host := req.Header.Get("X-Forwarded-Host")
if host == "" {
host = req.Host
}
return host
}
func ListContextValue(ctx interface{}, inner bool) {
contextValues := reflect.ValueOf(ctx).Elem()
contextKeys := reflect.TypeOf(ctx).Elem()
if !inner {
fmt.Printf("\nFields for %s.%s\n", contextKeys.PkgPath(), contextKeys.Name())
}
if contextKeys.Kind() == reflect.Struct {
for i := 0; i < contextValues.NumField(); i++ {
reflectValue := contextValues.Field(i)
reflectValue = reflect.NewAt(reflectValue.Type(), unsafe.Pointer(reflectValue.UnsafeAddr())).Elem()
reflectField := contextKeys.Field(i)
if reflectField.Name == "Context" {
ListContextValue(reflectValue.Interface(), true)
} else {
fmt.Printf("field name: %+v\n", reflectField.Name)
fmt.Printf("value: %+v\n", reflectValue.Interface())
}
}
} else {
fmt.Printf("context is empty (int)\n")
}
}