| 1 |
// Copyright (c) 2021, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package tdhttp |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"io" |
| 12 |
"net/http" |
| 13 |
"os" |
| 14 |
"path/filepath" |
| 15 |
"strings" |
| 16 |
) |
| 17 |
|
| 18 |
const ( |
| 19 |
defaultMediaType = "multipart/form-data" |
| 20 |
defaultBoundary = "go-testdeep-42" |
| 21 |
) |
| 22 |
|
| 23 |
// MultipartBody is a body of a multipart/form-data HTTP request (by |
| 24 |
// default, or any other multipart/… body, see MediaType field) as |
| 25 |
// defined in [RFC 2046] to be used as a [io.Reader] body of |
| 26 |
// [http.Request] and so compliant with [RFC 2388]. It implements |
| 27 |
// [io.Reader] and can only be read once. See [PostMultipartFormData] |
| 28 |
// and [TestAPI.PostMultipartFormData] for examples of use. |
| 29 |
// |
| 30 |
// [RFC 2046]: https://tools.ietf.org/html/rfc2046 |
| 31 |
// [RFC 2388]: https://tools.ietf.org/html/rfc2388 |
| 32 |
type MultipartBody struct { |
| 33 |
MediaType string // type to use instead of default "multipart/form-data" |
| 34 |
Boundary string // boundary to use between parts. Automatically initialized when calling ContentType(). |
| 35 |
Parts []*MultipartPart // parts composing this multipart/… body. |
| 36 |
content io.Reader |
| 37 |
} |
| 38 |
|
| 39 |
// Read implements [io.Reader] interface. |
| 40 |
func (b *MultipartBody) Read(p []byte) (n int, err error) { |
| 41 |
if b.content == nil { |
| 42 |
if b.Boundary == "" { |
| 43 |
b.Boundary = defaultBoundary |
| 44 |
} |
| 45 |
|
| 46 |
between := []byte("\r\n--" + b.Boundary + "\r\n") |
| 47 |
first := between[2:] |
| 48 |
end := []byte("\r\n--" + b.Boundary + "--\r\n") |
| 49 |
|
| 50 |
readers := make([]io.Reader, 0, len(b.Parts)*2+3) |
| 51 |
|
| 52 |
readers = append(readers, bytes.NewReader(first)) |
| 53 |
for i, part := range b.Parts { |
| 54 |
if i > 0 { |
| 55 |
readers = append(readers, bytes.NewReader(between)) |
| 56 |
} |
| 57 |
readers = append(readers, part) |
| 58 |
} |
| 59 |
readers = append(readers, bytes.NewReader(end)) |
| 60 |
|
| 61 |
b.content = io.MultiReader(readers...) |
| 62 |
} |
| 63 |
|
| 64 |
return b.content.Read(p) |
| 65 |
} |
| 66 |
|
| 67 |
// ContentType returns the Content-Type header to use. As it contains |
| 68 |
// the boundary, it is initialized first if it is still empty. By |
| 69 |
// default the media type is multipart/form-data but it can be |
| 70 |
// overridden using the MediaType field. |
| 71 |
// |
| 72 |
// m.MediaType = "multipart/mixed" |
| 73 |
// ct := m.ContentType() |
| 74 |
func (b *MultipartBody) ContentType() string { |
| 75 |
mt := b.MediaType |
| 76 |
if mt == "" { |
| 77 |
mt = defaultMediaType |
| 78 |
} |
| 79 |
|
| 80 |
if b.Boundary == "" { |
| 81 |
b.Boundary = defaultBoundary |
| 82 |
} |
| 83 |
|
| 84 |
return mt + `; boundary="` + b.Boundary + `"` |
| 85 |
} |
| 86 |
|
| 87 |
// MultipartPart is a part in a [MultipartBody] body. It implements io.Reader |
| 88 |
// and can only be read once. |
| 89 |
type MultipartPart struct { |
| 90 |
Name string // is "name" in Content-Disposition. If empty, Content-Disposition header is omitted. |
| 91 |
Filename string // is optional. If set it is "filename" in Content-Disposition. |
| 92 |
Content io.Reader // is the body section of the part. |
| 93 |
Header http.Header // is the header of the part and is optional. It is automatically initialized when needed. |
| 94 |
headerDone bool |
| 95 |
} |
| 96 |
|
| 97 |
// NewMultipartPart returns a new [MultipartPart] based on body |
| 98 |
// content. If body is nil, it means there is no body at all. |
| 99 |
func NewMultipartPart(name string, body io.Reader, contentType ...string) *MultipartPart { |
| 100 |
p := MultipartPart{ |
| 101 |
Name: name, |
| 102 |
Content: body, |
| 103 |
} |
| 104 |
if len(contentType) > 0 { |
| 105 |
p.Header = http.Header{"Content-Type": contentType[:1]} |
| 106 |
} |
| 107 |
return &p |
| 108 |
} |
| 109 |
|
| 110 |
// NewMultipartPartFile returns a new [MultipartPart] based on |
| 111 |
// filePath content. If filePath cannot be opened, an error is |
| 112 |
// returned on first Read() call. |
| 113 |
func NewMultipartPartFile(name string, filePath string, contentType ...string) *MultipartPart { |
| 114 |
p := NewMultipartPart(name, &fileReader{filePath: filePath}, contentType...) |
| 115 |
p.Filename = filepath.Base(filePath) |
| 116 |
return p |
| 117 |
} |
| 118 |
|
| 119 |
// NewMultipartPartString returns a new [MultipartPart] based on body content. |
| 120 |
func NewMultipartPartString(name string, body string, contentType ...string) *MultipartPart { |
| 121 |
return NewMultipartPart(name, strings.NewReader(body), contentType...) |
| 122 |
} |
| 123 |
|
| 124 |
// NewMultipartPartBytes returns a new [MultipartPart] based on body content. |
| 125 |
func NewMultipartPartBytes(name string, body []byte, contentType ...string) *MultipartPart { |
| 126 |
return NewMultipartPart(name, bytes.NewReader(body), contentType...) |
| 127 |
} |
| 128 |
|
| 129 |
// Read implements [io.Reader] interface. |
| 130 |
func (p *MultipartPart) Read(b []byte) (n int, err error) { |
| 131 |
if !p.headerDone { |
| 132 |
// Header not yet computed |
| 133 |
if p.Header == nil { |
| 134 |
p.Header = http.Header{} |
| 135 |
} |
| 136 |
if p.Name != "" && p.Header.Get("Content-Disposition") == "" { |
| 137 |
val := `form-data; name="` + p.Name + `"` |
| 138 |
if p.Filename != "" { |
| 139 |
val += `; filename="` + p.Filename + `"` |
| 140 |
} |
| 141 |
p.Header.Set("Content-Disposition", val) |
| 142 |
} |
| 143 |
|
| 144 |
readers := make([]io.Reader, 1, 3) |
| 145 |
if p.Content != nil { |
| 146 |
if p.Header.Get("Content-Type") == "" { |
| 147 |
var head bytes.Buffer |
| 148 |
copied, err := io.CopyN(&head, p.Content, 512) |
| 149 |
if err != nil && err != io.EOF { |
| 150 |
return 0, err |
| 151 |
} |
| 152 |
if copied > 0 { |
| 153 |
p.Header.Set("Content-Type", http.DetectContentType(head.Bytes())) |
| 154 |
readers = append(readers, &head, p.Content) |
| 155 |
} |
| 156 |
} else { |
| 157 |
readers = append(readers, p.Content) |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
var header bytes.Buffer |
| 162 |
p.Header.Write(&header) //nolint: errcheck |
| 163 |
if len(readers) > 1 { |
| 164 |
header.WriteString("\r\n") |
| 165 |
} |
| 166 |
readers[0] = &header |
| 167 |
|
| 168 |
p.Content = io.MultiReader(readers...) |
| 169 |
|
| 170 |
p.headerDone = true |
| 171 |
} |
| 172 |
|
| 173 |
return p.Content.Read(b) |
| 174 |
} |
| 175 |
|
| 176 |
type fileReader struct { |
| 177 |
filePath string |
| 178 |
file *os.File |
| 179 |
err error |
| 180 |
} |
| 181 |
|
| 182 |
func (f *fileReader) Read(b []byte) (n int, err error) { |
| 183 |
if f.err != nil { |
| 184 |
return 0, f.err |
| 185 |
} |
| 186 |
if f.file == nil { |
| 187 |
file, err := os.Open(f.filePath) |
| 188 |
if err != nil { |
| 189 |
f.err = err |
| 190 |
return 0, err |
| 191 |
} |
| 192 |
f.file = file |
| 193 |
} |
| 194 |
n, err = f.file.Read(b) |
| 195 |
if err != nil { // At EOF, (*os.File).Read() returns 0, io.EOF |
| 196 |
f.err = err |
| 197 |
f.file.Close() //nolint: errcheck |
| 198 |
f.file = nil |
| 199 |
} |
| 200 |
return |
| 201 |
} |