-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
file.go
62 lines (48 loc) · 1018 Bytes
/
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
package rek
import (
"bytes"
"io"
"mime/multipart"
"os"
"path/filepath"
)
const defaultFileFieldName = "file"
type file struct {
FieldName string
Filepath string
Params map[string]string
}
func (f *file) build() *file {
if f.FieldName == "" {
f.FieldName = defaultFileFieldName
}
return f
}
func buildMultipartBody(opts *options) (io.Reader, string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
f := opts.file.build()
file, err := os.Open(f.Filepath)
if err != nil {
return nil, "", err
}
defer file.Close()
part, err := writer.CreateFormFile(f.FieldName, filepath.Base(f.Filepath))
if err != nil {
return nil, "", err
}
if _, err := io.Copy(part, file); err != nil {
return nil, "", err
}
if f.Params != nil {
for k, v := range f.Params {
if err := writer.WriteField(k, v); err != nil {
return nil, "", err
}
}
}
if err := writer.Close(); err != nil {
return nil, "", err
}
return body, writer.FormDataContentType(), nil
}