-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultipart.go
More file actions
118 lines (96 loc) · 2.07 KB
/
multipart.go
File metadata and controls
118 lines (96 loc) · 2.07 KB
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
package rpc
import (
"io"
"os"
"bytes"
"mime/multipart"
)
type Attachment struct{
FileName string
FilePath string
}
type MultipartForm struct{
build bool
content_type string
buffer *bytes.Buffer
fields map[string]string
attachments map[string]Attachment
}
func NewMultipartForm() *MultipartForm {
var b bytes.Buffer
return &MultipartForm{
build: false,
buffer: &b,
fields: make(map[string]string),
attachments: make(map[string]Attachment),
}
}
func (form *MultipartForm) AddField(field, value string) {
form.fields[field] = value
}
func (form *MultipartForm) AddAttachment(field, filename, filepath string) {
form.attachments[field] = Attachment{FileName:filename, FilePath:filepath}
}
func (form *MultipartForm) DelField(field string) {
delete(form.fields, field)
delete(form.attachments, field)
}
func (form *MultipartForm) Build() error {
if form.build {
return nil
}
w := multipart.NewWriter(form.buffer)
for k, v := range form.fields {
if err := w.WriteField(k, v); err != nil {
return err
}
}
for k, v := range form.attachments {
p, err := w.CreateFormFile(k, v.FileName)
if err != nil {
return err
}
f, err := os.Open(v.FilePath)
if err != nil {
return err
}
defer f.Close()
// finfo, err := f.Stat()
// if err != nil {
// return err
// }
// fsize := finfo.Size()
if _, err := io.Copy(p, f); err != nil {
return err
}
}
if err := w.Close(); err != nil {
return err
}
form.content_type = w.FormDataContentType()
return nil
}
func (form *MultipartForm) ContentType() (string, error) {
if err := form.Build(); err != nil {
return "", err
}
return form.content_type, nil
}
func (form *MultipartForm) Reader() (io.Reader, error) {
if err := form.Build(); err != nil {
return nil, err
}
return form.buffer, nil
}
func (form *MultipartForm) Size() (int, error) {
if err := form.Build(); err != nil {
return 0, err
}
return form.buffer.Len(), nil
}
func (form *MultipartForm) Bytes() ([]byte, error) {
if err := form.Build(); err != nil {
return nil, err
}
return form.buffer.Bytes(), nil
}