MCPcopy Create free account
hub / github.com/Pagghiu/SaneCppLibraries / postMultipart

Method postMultipart

Tests/Libraries/Http/HttpTestClient.cpp:162–250  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

160 parser.type = HttpParser::Type::Response;
161 responseHasNoBody = false;
162 return connectAsync.start(*eventLoop, clientSocket, localHost);
163}
164
165SC::Result SC::HttpTestClient::postMultipart(AsyncEventLoop& loop, StringSpan url, StringSpan fieldName,
166 StringSpan fileName, StringSpan fileContent, TimeMs delay)
167{
168 bodyDelay = delay;
169 eventLoop = &loop;
170 responseHasNoBody = false;
171
172 uint16_t port;
173 HttpURLParser urlParser;
174 SC_TRY(urlParser.parse(url));
175 if (urlParser.protocol != "http")
176 return Result::Error(HttpResultCategory, HttpError::UnsupportedProtocol);
177 // TODO: Make DNS Resolution asynchronous
178 char buffer[256];
179 Span<char> ipAddress = {buffer};
180 SC_TRY(SocketDNS::resolveDNS(urlParser.hostname, ipAddress))
181 port = urlParser.port;
182 SocketIPAddress localHost;
183 SC_TRY(localHost.fromAddressPort({ipAddress, true, StringEncoding::Ascii}, port));
184 SC_TRY(eventLoop->createAsyncTCPSocket(localHost.getAddressFamily(), clientSocket));
185
186 // Generate a unique boundary
187 StringSpan boundary = "----SCFormBoundary7MA4YWxkTrZu0gW";
188 size_t boundaryLen = boundary.sizeInBytes();
189
190 {
191 GrowableBuffer<decltype(content)> gb = {content};
192
193 HttpStringAppend& sb = static_cast<HttpStringAppend&>(static_cast<IGrowableBuffer&>(gb));
194 sb.clear();
195
196 // Build the multipart body first to know content length
197 // Body format:
198 // --boundary\r\n
199 // Content-Disposition: form-data; name="fieldName"; filename="fileName"\r\n
200 // Content-Type: application/octet-stream\r\n
201 // \r\n
202 // fileContent
203 // \r\n--boundary--\r\n
204
205 // Calculate body size
206 size_t bodySize = 0;
207 bodySize += 2 + boundaryLen + 2; // --boundary\r\n
208 bodySize += 38 + fieldName.sizeInBytes() + 13 + fileName.sizeInBytes() + 3; // Content-Disposition: ...\r\n
209 bodySize += 40; // Content-Type: application/octet-stream\r\n
210 bodySize += 2; // \r\n
211 bodySize += fileContent.sizeInBytes(); // file content
212 bodySize += 4 + boundaryLen + 4; // \r\n--boundary--\r\n
213
214 // Build HTTP headers
215 SC_TRY(sb.append("POST "));
216 SC_TRY(sb.append(urlParser.path));
217 SC_TRY(sb.append(" HTTP/1.1\r\n"));
218 SC_TRY(sb.append("User-agent: SC\r\n"));
219 SC_TRY(sb.append("Host: 127.0.0.1\r\n"));

Callers 3

uploadsDisabledMethod · 0.45
httpFileServerTestMethod · 0.45
multipartUploadMethod · 0.45

Calls 8

createAsyncTCPSocketMethod · 0.80
getAddressFamilyMethod · 0.80
parseMethod · 0.45
sizeInBytesMethod · 0.45
clearMethod · 0.45
appendMethod · 0.45
sizeMethod · 0.45
startMethod · 0.45

Tested by

no test coverage detected