-
Notifications
You must be signed in to change notification settings - Fork 0
/
multipart.go
58 lines (48 loc) · 1001 Bytes
/
multipart.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
package gohttp
import (
"bytes"
"io"
"mime/multipart"
"os"
"path/filepath"
)
// File contains the file part of a multipart message.
type File struct {
io.ReadCloser
Fieldname string
Filename string
}
// F opens the file for creating File.
func F(fieldname, filename string) *File {
f, err := os.Open(filename)
if err != nil {
panic(err)
}
return &File{
ReadCloser: f,
Fieldname: fieldname,
Filename: filepath.Base(filename),
}
}
func buildMultipart(params map[string]string, files ...*File) (io.Reader, string, error) {
data := new(bytes.Buffer)
w := multipart.NewWriter(data)
defer w.Close()
for _, file := range files {
if file == nil {
continue
}
defer file.Close()
part, err := w.CreateFormFile(file.Fieldname, file.Filename)
if err != nil {
return nil, "", err
}
if _, err := io.Copy(part, file); err != nil {
return nil, "", err
}
}
for k, v := range params {
w.WriteField(k, v)
}
return data, w.FormDataContentType(), nil
}