-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathfile.go
65 lines (57 loc) · 1.39 KB
/
file.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
package httptest
import (
"bytes"
"io"
"mime/multipart"
"net/http"
)
type File struct {
io.Reader
ParamName string
FileName string
}
func (r *Request) MultiPartPost(body interface{}, files ...File) (*Response, error) {
req, err := newMultipart(r.URL, "POST", body, files...)
if err != nil {
return nil, err
}
return r.Perform(req), nil
}
func (r *Request) MultiPartPut(body interface{}, files ...File) (*Response, error) {
req, err := newMultipart(r.URL, "PUT", body, files...)
if err != nil {
return nil, err
}
return r.Perform(req), nil
}
// this helper method was inspired by this blog post by Matt Aimonetti:
// https://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
func newMultipart(url string, method string, body interface{}, files ...File) (*http.Request, error) {
bb := &bytes.Buffer{}
writer := multipart.NewWriter(bb)
defer writer.Close()
for _, f := range files {
part, err := writer.CreateFormFile(f.ParamName, f.FileName)
if err != nil {
return nil, err
}
_, err = io.Copy(part, f)
if err != nil {
return nil, err
}
}
for k, v := range toURLValues(body) {
for _, vv := range v {
err := writer.WriteField(k, vv)
if err != nil {
return nil, err
}
}
}
req, err := http.NewRequest(method, url, bb)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, nil
}