-
Notifications
You must be signed in to change notification settings - Fork 0
/
composer.go
266 lines (239 loc) · 7.83 KB
/
composer.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Package composer prepares bodies of HTTP requests with MIME multipart
// messages without reading entire file contents to memory. Instead of writing
// files to multipart Writer right away, it collects Readers for each part
// of the form and lets them stream to the network once the request has been
// sent. Avoids buffering of the request body simpler than with goroutines
// and pipes.
//
// Text fields and files can be appended by convenience methods:
//
// comp := composer.NewComposer()
// comp.AddField("comment", "a comment")
// err := comp.AddFile("file", "test.txt")
//
// The multipart form-data content type and a reader for the full request
// body can be passed directly the HTTP request methods. They close a
// closable writer even in case of failure:
//
// resp, err := http.DefaultClient.Post("http://host.com/upload",
// comp.FormDataContentType(), comp.DetachReader())
package composer
import (
"crypto/rand"
"errors"
"fmt"
"io"
"mime"
"path/filepath"
"strings"
"github.com/prantlf/go-sizeio"
)
// A Composer generates multipart messages with delayed content supplied
// by readers.
type Composer struct {
// CloseReaders, if set to false, prevents closing of added files
// or readers when Close is called, or when the reader returned by
// DetachReader is closed. The initial value set by NewComposer is true.
CloseReaders bool
boundary string
readers []io.Reader
}
// NewComposer returns a new multipart message Composer with a random
// boundary.
func NewComposer() *Composer {
return &Composer{boundary: randomBoundary(), CloseReaders: true}
}
// Boundary returns the Composer's boundary.
func (c *Composer) Boundary() string {
return c.boundary
}
// SetBoundary overrides the Composer's initial boundary separator
// with an explicit value.
//
// SetBoundary must be called before any parts are added, may only
// contain certain ASCII characters, and must be non-empty and
// at most 70 bytes long.
func (c *Composer) SetBoundary(boundary string) error {
if len(c.readers) > 0 {
return errors.New("multipart: SetBoundary called after add")
}
// rfc2046#section-5.1.1
if len(boundary) < 1 || len(boundary) > 70 {
return errors.New("multipart: invalid boundary length")
}
end := len(boundary) - 1
for i, c := range boundary {
if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
continue
}
switch c {
case '\'', '(', ')', '+', '_', ',', '-', '.', '/', ':', '=', '?':
continue
case ' ':
if i != end {
continue
}
}
return errors.New("multipart: invalid boundary character")
}
c.boundary = boundary
return nil
}
// ResetBoundary overrides the Composer's current boundary separator
// with a randomly generared one.
//
// ResetBoundary must be called before any parts are added.
func (c *Composer) ResetBoundary() error {
if len(c.readers) > 0 {
return errors.New("multipart: RandomizeBoundary called after add")
}
c.boundary = randomBoundary()
return nil
}
// FormDataContentType returns the Content-Type for an HTTP
// multipart/form-data with this Composers's Boundary.
func (c *Composer) FormDataContentType() string {
boundary := c.boundary
// Quote the boundary if it contains any of the special characters
// defined by RFC 2045, or space.
if strings.ContainsAny(boundary, `()<>@,;:\"/[]?= `) {
boundary = `"` + boundary + `"`
}
return "multipart/form-data; boundary=" + boundary
}
// AddField is a convenience wrapper around AddFileReader. It creates
// a new multipart section with the provided field name and value.
func (c *Composer) AddField(name, value string) {
c.AddFieldReader(name, strings.NewReader(value))
}
// AddFieldReader creates a new multipart section with a field value.
// It inserts a header using the given field name and then appends
// the value reader.
func (c *Composer) AddFieldReader(name string, reader io.Reader) {
c.readers = append(c.readers,
strings.NewReader(fmt.Sprintf("%s\r\n\r\n", c.partPrefix(name))), reader)
}
// AddFile is a convenience wrapper around AddFileReader. It creates a new
// multipart section with the provided field name and file content.
func (c *Composer) AddFile(fieldName, filePath string) error {
if !c.CloseReaders {
return errors.New("multipart: adding file by path forbidden")
}
reader, err := sizeio.OpenFile(filePath)
if err != nil {
return err
}
c.AddFileReader(fieldName, filepath.Base(filePath), reader)
return nil
}
// AddFileReader creates a new multipart section with a file content.
// It inserts a header using the given field name, file name and the content
// type inferred from the file extension, then appends the file reader.
func (c *Composer) AddFileReader(fieldName, fileName string, reader io.Reader) {
contentType := mime.TypeByExtension(filepath.Ext(fileName))
if contentType == "" {
contentType = "application/octet-stream"
}
c.readers = append(c.readers, strings.NewReader(
fmt.Sprintf("%s; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n",
c.partPrefix(fieldName), escapeQuotes(fileName), contentType)), reader)
}
// DetachReader finishes the multipart message by adding the trailing
// boundary end line to the output and moves the closable readers to be
// closed with the returned compound reader.
func (c *Composer) DetachReader() io.ReadCloser {
c.appendLastBoundary()
return c.detachReader()
}
// DetachReaderWithSize finishes the multipart message by adding the trailing
// boundary end line to the output and moves the closable readers to be
// closed with the returned compound reader. It tries computing the total
// request body size, which will work if size was available for all readers.
//
// If it fails, the composer instance will not be closed.
func (c *Composer) DetachReaderWithSize() (io.ReadCloser, int64, error) {
c.appendLastBoundary()
size, err := c.totalSize()
if err != nil {
return nil, 0, err
}
allReader := c.detachReader()
return allReader, size, nil
}
// Clear closes all closable readers added by AddFileReader or AddFile and
// clears their collection, making the composer ready to start empty again.
func (c *Composer) Clear() {
c.Close()
c.readers = nil
}
// Close closes all closable readers added by AddFileReader or AddFile.
// If some of them fail, the first error will be returned.
func (c *Composer) Close() error {
if c.CloseReaders {
return closeAll(c.readers)
}
return nil
}
type composedReader struct {
io.Reader
readers []io.Reader
}
func (r composedReader) Close() error {
return closeAll(r.readers)
}
func (c *Composer) totalSize() (int64, error) {
var size int64
for _, reader := range c.readers {
if withSize, ok := reader.(sizeio.WithSize); ok {
size += withSize.Size()
} else {
return 0, errors.New("multipart: reader without size encountered")
}
}
return size, nil
}
func (c *Composer) detachReader() io.ReadCloser {
var readers []io.Reader
if c.CloseReaders {
readers = c.readers
}
allReader := composedReader{io.MultiReader(c.readers...), readers}
c.readers = nil
return allReader
}
func closeAll(readers []io.Reader) error {
var firstErr error
for _, reader := range readers {
if closer, ok := reader.(io.ReadCloser); ok {
err := closer.Close()
if err != nil && firstErr == nil {
firstErr = err
}
}
}
return firstErr
}
func (c *Composer) appendLastBoundary() {
c.readers = append(c.readers,
strings.NewReader(fmt.Sprintf("\r\n--%s--\r\n", c.boundary)))
}
func (c *Composer) partPrefix(name string) string {
var delimiter string
if len(c.readers) > 0 {
delimiter = "\r\n"
}
return fmt.Sprintf("%s--%s\r\nContent-Disposition: form-data; name=\"%s\"",
delimiter, c.boundary, escapeQuotes(name))
}
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(value string) string {
return quoteEscaper.Replace(value)
}
func randomBoundary() string {
var buf [30]byte
_, err := io.ReadFull(rand.Reader, buf[:])
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", buf[:])
}