forked from Automattic/wpgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetcher.go
121 lines (99 loc) · 2.28 KB
/
fetcher.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
//
// A library to make it a bit easier to do HTTP fetches
// supports adding headers, posting forms, parameters
// and uploading files
//
package main
import (
"bytes"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type Fetcher struct {
Params, Header, Files map[string]string
}
// NewFetcher creates a fetcher request instance
func NewFetcher() (f Fetcher) {
f.Params = map[string]string{}
f.Header = map[string]string{}
f.Files = map[string]string{}
return f
}
// Fetch executes the fetcher request
func (f Fetcher) Fetch(url, method string) (result string, err error) {
var reqBody io.Reader
var contentType string
// check if post and add post params
if method == "POST" {
reqBody, contentType, err = f.createPostBody()
if err != nil {
return "", err
}
} else {
method = "GET"
}
// build request object
client := &http.Client{}
request, err := http.NewRequest(method, url, reqBody)
if err != nil {
return "", err
}
// need to add header to request for content-type
// this sets boundaries and builds proper header type
if method == "POST" {
request.Header.Add("Content-Type", contentType)
}
// add additional user header values
for k, v := range f.Header {
request.Header.Add(k, v)
}
// execute request
res, err := client.Do(request)
if err != nil {
return "", err
}
// process response
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
result = string(body)
return
}
// create body for post - includes files, params
func (f Fetcher) createPostBody() (body io.Reader, contentType string, err error) {
var b bytes.Buffer
writer := multipart.NewWriter(&b)
// add files if we are uploading a file
for k, v := range f.Files {
file, err := os.Open(v)
if err != nil {
return nil, "", err
}
part, err := writer.CreateFormFile(k, filepath.Base(v))
if err != nil {
return nil, "", err
}
_, err = io.Copy(part, file)
if err != nil {
return nil, "", err
}
}
// add parameters if there are parameters
for k, v := range f.Params {
_ = writer.WriteField(k, v)
}
err = writer.Close()
if err != nil {
return
}
// content type might be different due to file uploads
contentType = writer.FormDataContentType()
body = &b
return body, contentType, nil
}