-
Notifications
You must be signed in to change notification settings - Fork 8
/
multipart_request.go
44 lines (39 loc) · 1.05 KB
/
multipart_request.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
package multipartutil
import (
"net/http"
"net/url"
"github.com/grokify/mogo/net/httputilmore"
)
// FileInfo represents a file for uploading.
type FileInfo struct {
MIMEPartName string
Filepath string
}
// NewRequest returns a `*http.Request` for making a
// request using multipart/form-data. It supports simple strings
// and files. For more complex field requirements such as JSON
// body parts that require Content-Type headers and Base64
// encoding, use MultipartBuilder directly.
func NewRequest(method, url string, params url.Values, files []FileInfo) (*http.Request, error) {
mb := NewMultipartBuilder()
err := mb.WriteURLValues(params)
if err != nil {
return nil, err
}
for _, file := range files {
err := mb.WriteFilePathPlus(file.MIMEPartName, file.Filepath, true)
if err != nil {
return nil, err
}
}
err = mb.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, url, mb.Buffer)
if err != nil {
return nil, err
}
req.Header.Set(httputilmore.HeaderContentType, mb.ContentType())
return req, nil
}