/
httpclient.go
118 lines (105 loc) · 2.57 KB
/
httpclient.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
package httpclient
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type HttpClient struct {
api string
hasSSL bool
// queryID bson.ObjectId
}
//NewHttpClient -
func NewHttpClient(hasSSL bool) *HttpClient {
c := &HttpClient{}
// c.queryID = queryID
c.hasSSL = hasSSL
return c
}
//Connect - connect HTTP connection with specific url and method
func (c *HttpClient) Connect(url string, method string, params map[string]string, reqBody io.Reader) ([]byte, error) {
log.Println("url=", url)
client := &http.Client{}
//habdle non-ssl way for local testing.
if !c.hasSSL {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{Transport: tr}
}
request, err := http.NewRequest(method, url, reqBody)
if method == "POST" {
request.Header.Set("Content-Type", "application/json")
}
//handle query string
q := request.URL.Query()
for k, v := range params {
q.Add(k, v)
}
request.URL.RawQuery = q.Encode()
fmt.Println(request.URL.String())
response, err := client.Do(request)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(response.Body)
defer response.Body.Close()
if err != nil {
return nil, err
}
return body, nil
}
//ConnectWithMultpart -
func (c *HttpClient) ConnectWithMultpart(url string, method string, params map[string]string, fileParaname, filePath string) ([]byte, error) {
client := &http.Client{}
request, err := newfileUploadRequest(url, params, fileParaname, filePath)
if err != nil {
log.Fatal(err)
return nil, err
}
if !c.hasSSL {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{Transport: tr}
}
resp, err := client.Do(request)
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}
return body, nil
}
func newfileUploadRequest(uri string, params map[string]string, paramName string, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", uri, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
// log.Println("completed request")
return req, err
}