-
Notifications
You must be signed in to change notification settings - Fork 0
/
httputils.go
85 lines (79 loc) · 2.08 KB
/
httputils.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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package httputil provides HTTP functions for internal usage only.
package httputil
import (
"net/http"
"strings"
"github.com/gogf/gf/v2/encoding/gurl"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
const (
fileUploadingKey = "@file:"
)
// BuildParams builds the request string for the http client. The `params` can be type of:
// string/[]byte/map/struct/*struct.
//
// The optional parameter `noUrlEncode` specifies whether ignore the url encoding for the data.
func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) {
// If given string/[]byte, converts and returns it directly as string.
switch v := params.(type) {
case string, []byte:
return gconv.String(params)
case []interface{}:
if len(v) > 0 {
params = v[0]
} else {
params = nil
}
}
// Else converts it to map and does the url encoding.
m, urlEncode := gconv.Map(params), true
if len(m) == 0 {
return gconv.String(params)
}
if len(noUrlEncode) == 1 {
urlEncode = !noUrlEncode[0]
}
// If there's file uploading, it ignores the url encoding.
if urlEncode {
for k, v := range m {
if gstr.Contains(k, fileUploadingKey) || gstr.Contains(gconv.String(v), fileUploadingKey) {
urlEncode = false
break
}
}
}
s := ""
for k, v := range m {
if len(encodedParamStr) > 0 {
encodedParamStr += "&"
}
s = gconv.String(v)
if urlEncode {
if strings.HasPrefix(s, fileUploadingKey) && len(s) > len(fileUploadingKey) {
// No url encoding if uploading file.
} else {
s = gurl.Encode(s)
}
}
encodedParamStr += k + "=" + s
}
return
}
// HeaderToMap coverts request headers to map.
func HeaderToMap(header http.Header) map[string]interface{} {
m := make(map[string]interface{})
for k, v := range header {
if len(v) > 1 {
m[k] = v
} else {
m[k] = v[0]
}
}
return m
}