@@ -4,8 +4,12 @@ import (
4
4
"compress/gzip"
5
5
"context"
6
6
"fmt"
7
+ "io"
8
+ "mime/multipart"
7
9
"net/http"
8
10
"net/http/httptest"
11
+ "net/http/httputil"
12
+ "net/textproto"
9
13
"strings"
10
14
11
15
"github.com/carlmjohnson/requests"
@@ -100,3 +104,59 @@ func ExampleTestServerConfig() {
100
104
// Hello, world!
101
105
// Howdy, planet!
102
106
}
107
+
108
+ func ExampleBodyMultipart () {
109
+ req , err := requests .
110
+ URL ("http://example.com" ).
111
+ Config (requests .BodyMultipart ("abc" , func (multi * multipart.Writer ) error {
112
+ // CreateFormFile hardcodes the Content-Type as application/octet-stream
113
+ w , err := multi .CreateFormFile ("file" , "en.txt" )
114
+ if err != nil {
115
+ return err
116
+ }
117
+ _ , err = io .WriteString (w , "Hello, World!" )
118
+ if err != nil {
119
+ return err
120
+ }
121
+ // CreatePart is more flexible and lets you add headers
122
+ h := make (textproto.MIMEHeader )
123
+ h .Set ("Content-Disposition" , `form-data; name="file"; filename="jp.txt"` )
124
+ h .Set ("Content-Type" , "text/plain; charset=utf-8" )
125
+ w , err = multi .CreatePart (h )
126
+ if err != nil {
127
+ panic (err )
128
+ }
129
+ _ , err = io .WriteString (w , "こんにちは世界!" )
130
+ if err != nil {
131
+ return err
132
+ }
133
+ return nil
134
+ })).
135
+ Request (context .Background ())
136
+ if err != nil {
137
+ panic (err )
138
+ }
139
+ b , err := httputil .DumpRequest (req , true )
140
+ if err != nil {
141
+ panic (err )
142
+ }
143
+
144
+ // Make carriage return visible
145
+ fmt .Println (strings .ReplaceAll (string (b ), "\r " , "↵" ))
146
+ // Output:
147
+ // POST / HTTP/1.1↵
148
+ // Host: example.com↵
149
+ // Content-Type: multipart/form-data; boundary=abc↵
150
+ // ↵
151
+ // --abc↵
152
+ // Content-Disposition: form-data; name="file"; filename="en.txt"↵
153
+ // Content-Type: application/octet-stream↵
154
+ // ↵
155
+ // Hello, World!↵
156
+ // --abc↵
157
+ // Content-Disposition: form-data; name="file"; filename="jp.txt"↵
158
+ // Content-Type: text/plain; charset=utf-8↵
159
+ // ↵
160
+ // こんにちは世界!↵
161
+ // --abc--↵
162
+ }
0 commit comments