/
httpUtil.go
93 lines (86 loc) · 2.49 KB
/
httpUtil.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
package util
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
type UploadFile struct {
// 表单名称
Name string
// 文件全路径
Filepath string
}
func PostForm(reqUrl string, reqParams map[string]string, headers map[string]string) string {
return post(reqUrl, reqParams, "application/x-www-form-urlencoded", nil, headers)
}
func PostJson(reqUrl string, reqParams map[string]string, headers map[string]string) string {
return post(reqUrl, reqParams, "application/json", nil, headers)
}
func PostFile(reqUrl string, reqParams map[string]string, files []UploadFile, headers map[string]string) string {
return post(reqUrl, reqParams, "multipart/form-data", files, headers)
}
func post(reqUrl string, reqParams map[string]string, contentType string, files []UploadFile, headers map[string]string) string {
requestBody, realContentType := getReader(reqParams, contentType, files)
httpRequest, _ := http.NewRequest("POST", reqUrl, requestBody)
// 添加请求头
httpRequest.Header.Add("Content-Type", realContentType)
for k, v := range headers {
httpRequest.Header.Add(k, v)
}
// 发送请求
httpClient := &http.Client{}
resp, err := httpClient.Do(httpRequest)
if err != nil {
panic(err)
}
defer resp.Body.Close()
response, _ := ioutil.ReadAll(resp.Body)
return string(response)
}
func getReader(reqParams map[string]string, contentType string, files []UploadFile) (io.Reader, string) {
if strings.Contains(contentType, "json") {
bytesData, _ := json.Marshal(reqParams)
return bytes.NewReader(bytesData), contentType
} else if files != nil {
bodyBuffer := &bytes.Buffer{}
// 文件写入 body
writer := multipart.NewWriter(bodyBuffer)
for _, uploadFile := range files {
file, err := os.Open(uploadFile.Filepath)
if err != nil {
panic(err)
}
part, err := writer.CreateFormFile(uploadFile.Name, filepath.Base(uploadFile.Filepath))
if err != nil {
panic(err)
}
io.Copy(part, file)
file.Close()
}
// 其他参数列表写入 body
for k, v := range reqParams {
if err := writer.WriteField(k, v); err != nil {
panic(err)
}
}
if err := writer.Close(); err != nil {
panic(err)
}
// 上传文件需要自己专用的contentType
return bodyBuffer, writer.FormDataContentType()
} else {
urlValues := url.Values{}
for key, val := range reqParams {
urlValues.Set(key, val)
}
reqBody := urlValues.Encode()
return strings.NewReader(reqBody), contentType
}
}