http_examples.hpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. //
  2. // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #include <boost/beast.hpp>
  10. #include <iostream>
  11. /* This file contains the functions and classes found in the documentation
  12. They are compiled and run as part of the unit tests, so you can copy
  13. the code and use it in your own projects as a starting point for
  14. building a network application.
  15. */
  16. // The documentation assumes the boost::beast::http namespace
  17. namespace boost {
  18. namespace beast {
  19. namespace http {
  20. //------------------------------------------------------------------------------
  21. //
  22. // Example: Expect 100-continue
  23. //
  24. //------------------------------------------------------------------------------
  25. //[example_http_send_expect_100_continue
  26. /** Send a request with Expect: 100-continue
  27. This function will send a request with the Expect: 100-continue
  28. field by first sending the header, then waiting for a successful
  29. response from the server before continuing to send the body. If
  30. a non-successful server response is received, the function
  31. returns immediately.
  32. @param stream The remote HTTP server stream.
  33. @param buffer The buffer used for reading.
  34. @param req The request to send. This function modifies the object:
  35. the Expect header field is inserted into the message if it does
  36. not already exist, and set to "100-continue".
  37. @param ec Set to the error, if any occurred.
  38. */
  39. template<
  40. class SyncStream,
  41. class DynamicBuffer,
  42. class Body, class Allocator>
  43. void
  44. send_expect_100_continue(
  45. SyncStream& stream,
  46. DynamicBuffer& buffer,
  47. request<Body, basic_fields<Allocator>>& req,
  48. error_code& ec)
  49. {
  50. static_assert(is_sync_stream<SyncStream>::value,
  51. "SyncStream requirements not met");
  52. static_assert(
  53. boost::asio::is_dynamic_buffer<DynamicBuffer>::value,
  54. "DynamicBuffer requirements not met");
  55. // Insert or replace the Expect field
  56. req.set(field::expect, "100-continue");
  57. // Create the serializer
  58. request_serializer<Body, basic_fields<Allocator>> sr{req};
  59. // Send just the header
  60. write_header(stream, sr, ec);
  61. if(ec)
  62. return;
  63. // Read the response from the server.
  64. // A robust client could set a timeout here.
  65. {
  66. response<string_body> res;
  67. read(stream, buffer, res, ec);
  68. if(ec)
  69. return;
  70. if(res.result() != status::continue_)
  71. {
  72. // The server indicated that it will not
  73. // accept the request, so skip sending the body.
  74. return;
  75. }
  76. }
  77. // Server is OK with the request, send the body
  78. write(stream, sr, ec);
  79. }
  80. //]
  81. //[example_http_receive_expect_100_continue
  82. /** Receive a request, handling Expect: 100-continue if present.
  83. This function will read a request from the specified stream.
  84. If the request contains the Expect: 100-continue field, a
  85. status response will be delivered.
  86. @param stream The remote HTTP client stream.
  87. @param buffer The buffer used for reading.
  88. @param ec Set to the error, if any occurred.
  89. */
  90. template<
  91. class SyncStream,
  92. class DynamicBuffer>
  93. void
  94. receive_expect_100_continue(
  95. SyncStream& stream,
  96. DynamicBuffer& buffer,
  97. error_code& ec)
  98. {
  99. static_assert(is_sync_stream<SyncStream>::value,
  100. "SyncStream requirements not met");
  101. static_assert(
  102. boost::asio::is_dynamic_buffer<DynamicBuffer>::value,
  103. "DynamicBuffer requirements not met");
  104. // Declare a parser for a request with a string body
  105. request_parser<string_body> parser;
  106. // Read the header
  107. read_header(stream, buffer, parser, ec);
  108. if(ec)
  109. return;
  110. // Check for the Expect field value
  111. if(parser.get()[field::expect] == "100-continue")
  112. {
  113. // send 100 response
  114. response<empty_body> res;
  115. res.version(11);
  116. res.result(status::continue_);
  117. res.set(field::server, "test");
  118. write(stream, res, ec);
  119. if(ec)
  120. return;
  121. }
  122. // Read the rest of the message.
  123. //
  124. read(stream, buffer, parser, ec);
  125. }
  126. //]
  127. //------------------------------------------------------------------------------
  128. //
  129. // Example: Send Child Process Output
  130. //
  131. //------------------------------------------------------------------------------
  132. //[example_http_send_cgi_response
  133. /** Send the output of a child process as an HTTP response.
  134. The output of the child process comes from a @b SyncReadStream. Data
  135. will be sent continuously as it is produced, without the requirement
  136. that the entire process output is buffered before being sent. The
  137. response will use the chunked transfer encoding.
  138. @param input A stream to read the child process output from.
  139. @param output A stream to write the HTTP response to.
  140. @param ec Set to the error, if any occurred.
  141. */
  142. template<
  143. class SyncReadStream,
  144. class SyncWriteStream>
  145. void
  146. send_cgi_response(
  147. SyncReadStream& input,
  148. SyncWriteStream& output,
  149. error_code& ec)
  150. {
  151. static_assert(is_sync_read_stream<SyncReadStream>::value,
  152. "SyncReadStream requirements not met");
  153. static_assert(is_sync_write_stream<SyncWriteStream>::value,
  154. "SyncWriteStream requirements not met");
  155. // Set up the response. We use the buffer_body type,
  156. // allowing serialization to use manually provided buffers.
  157. response<buffer_body> res;
  158. res.result(status::ok);
  159. res.version(11);
  160. res.set(field::server, "Beast");
  161. res.set(field::transfer_encoding, "chunked");
  162. // No data yet, but we set more = true to indicate
  163. // that it might be coming later. Otherwise the
  164. // serializer::is_done would return true right after
  165. // sending the header.
  166. res.body().data = nullptr;
  167. res.body().more = true;
  168. // Create the serializer.
  169. response_serializer<buffer_body, fields> sr{res};
  170. // Send the header immediately.
  171. write_header(output, sr, ec);
  172. if(ec)
  173. return;
  174. // Alternate between reading from the child process
  175. // and sending all the process output until there
  176. // is no more output.
  177. do
  178. {
  179. // Read a buffer from the child process
  180. char buffer[2048];
  181. auto bytes_transferred = input.read_some(
  182. boost::asio::buffer(buffer, sizeof(buffer)), ec);
  183. if(ec == boost::asio::error::eof)
  184. {
  185. ec = {};
  186. // `nullptr` indicates there is no buffer
  187. res.body().data = nullptr;
  188. // `false` means no more data is coming
  189. res.body().more = false;
  190. }
  191. else
  192. {
  193. if(ec)
  194. return;
  195. // Point to our buffer with the bytes that
  196. // we received, and indicate that there may
  197. // be some more data coming
  198. res.body().data = buffer;
  199. res.body().size = bytes_transferred;
  200. res.body().more = true;
  201. }
  202. // Write everything in the body buffer
  203. write(output, sr, ec);
  204. // This error is returned by body_buffer during
  205. // serialization when it is done sending the data
  206. // provided and needs another buffer.
  207. if(ec == error::need_buffer)
  208. {
  209. ec = {};
  210. continue;
  211. }
  212. if(ec)
  213. return;
  214. }
  215. while(! sr.is_done());
  216. }
  217. //]
  218. //--------------------------------------------------------------------------
  219. //
  220. // Example: HEAD Request
  221. //
  222. //--------------------------------------------------------------------------
  223. //[example_http_do_head_response
  224. /** Handle a HEAD request for a resource.
  225. */
  226. template<
  227. class SyncStream,
  228. class DynamicBuffer
  229. >
  230. void do_server_head(
  231. SyncStream& stream,
  232. DynamicBuffer& buffer,
  233. error_code& ec)
  234. {
  235. static_assert(is_sync_stream<SyncStream>::value,
  236. "SyncStream requirements not met");
  237. static_assert(
  238. boost::asio::is_dynamic_buffer<DynamicBuffer>::value,
  239. "DynamicBuffer requirements not met");
  240. // We deliver this payload for all GET requests
  241. static std::string const payload = "Hello, world!";
  242. // Read the request
  243. request<string_body> req;
  244. read(stream, buffer, req, ec);
  245. if(ec)
  246. return;
  247. // Set up the response, starting with the common fields
  248. response<string_body> res;
  249. res.version(11);
  250. res.set(field::server, "test");
  251. // Now handle request-specific fields
  252. switch(req.method())
  253. {
  254. case verb::head:
  255. case verb::get:
  256. {
  257. // A HEAD request is handled by delivering the same
  258. // set of headers that would be sent for a GET request,
  259. // including the Content-Length, except for the body.
  260. res.result(status::ok);
  261. res.set(field::content_length, payload.size());
  262. // For GET requests, we include the body
  263. if(req.method() == verb::get)
  264. {
  265. // We deliver the same payload for GET requests
  266. // regardless of the target. A real server might
  267. // deliver a file based on the target.
  268. res.body() = payload;
  269. }
  270. break;
  271. }
  272. default:
  273. {
  274. // We return responses indicating an error if
  275. // we do not recognize the request method.
  276. res.result(status::bad_request);
  277. res.set(field::content_type, "text/plain");
  278. res.body() = "Invalid request-method '" + std::string(req.method_string()) + "'";
  279. res.prepare_payload();
  280. break;
  281. }
  282. }
  283. // Send the response
  284. write(stream, res, ec);
  285. if(ec)
  286. return;
  287. }
  288. //]
  289. //[example_http_do_head_request
  290. /** Send a HEAD request for a resource.
  291. This function submits a HEAD request for the specified resource
  292. and returns the response.
  293. @param res The response. This is an output parameter.
  294. @param stream The synchronous stream to use.
  295. @param buffer The buffer to use.
  296. @param target The request target.
  297. @param ec Set to the error, if any occurred.
  298. @throws std::invalid_argument if target is empty.
  299. */
  300. template<
  301. class SyncStream,
  302. class DynamicBuffer
  303. >
  304. response<empty_body>
  305. do_head_request(
  306. SyncStream& stream,
  307. DynamicBuffer& buffer,
  308. string_view target,
  309. error_code& ec)
  310. {
  311. // Do some type checking to be a good citizen
  312. static_assert(is_sync_stream<SyncStream>::value,
  313. "SyncStream requirements not met");
  314. static_assert(
  315. boost::asio::is_dynamic_buffer<DynamicBuffer>::value,
  316. "DynamicBuffer requirements not met");
  317. // The interfaces we are using are low level and do not
  318. // perform any checking of arguments; so we do it here.
  319. if(target.empty())
  320. throw std::invalid_argument("target may not be empty");
  321. // Build the HEAD request for the target
  322. request<empty_body> req;
  323. req.version(11);
  324. req.method(verb::head);
  325. req.target(target);
  326. req.set(field::user_agent, "test");
  327. // A client MUST send a Host header field in all HTTP/1.1 request messages.
  328. // https://tools.ietf.org/html/rfc7230#section-5.4
  329. req.set(field::host, "localhost");
  330. // Now send it
  331. write(stream, req, ec);
  332. if(ec)
  333. return {};
  334. // Create a parser to read the response.
  335. // We use the `empty_body` type since
  336. // a response to a HEAD request MUST NOT
  337. // include a body.
  338. response_parser<empty_body> p;
  339. // Inform the parser that there will be no body.
  340. p.skip(true);
  341. // Read the message. Even though fields like
  342. // Content-Length or Transfer-Encoding may be
  343. // set, the message will not contain a body.
  344. read(stream, buffer, p, ec);
  345. if(ec)
  346. return {};
  347. // Transfer ownership of the response to the caller.
  348. return p.release();
  349. }
  350. //]
  351. //------------------------------------------------------------------------------
  352. //
  353. // Example: HTTP Relay
  354. //
  355. //------------------------------------------------------------------------------
  356. //[example_http_relay
  357. /** Relay an HTTP message.
  358. This function efficiently relays an HTTP message from a downstream
  359. client to an upstream server, or from an upstream server to a
  360. downstream client. After the message header is read from the input,
  361. a user provided transformation function is invoked which may change
  362. the contents of the header before forwarding to the output. This may
  363. be used to adjust fields such as Server, or proxy fields.
  364. @param output The stream to write to.
  365. @param input The stream to read from.
  366. @param buffer The buffer to use for the input.
  367. @param transform The header transformation to apply. The function will
  368. be called with this signature:
  369. @code
  370. template<class Body>
  371. void transform(message<
  372. isRequest, Body, Fields>&, // The message to transform
  373. error_code&); // Set to the error, if any
  374. @endcode
  375. @param ec Set to the error if any occurred.
  376. @tparam isRequest `true` to relay a request.
  377. @tparam Fields The type of fields to use for the message.
  378. */
  379. template<
  380. bool isRequest,
  381. class SyncWriteStream,
  382. class SyncReadStream,
  383. class DynamicBuffer,
  384. class Transform>
  385. void
  386. relay(
  387. SyncWriteStream& output,
  388. SyncReadStream& input,
  389. DynamicBuffer& buffer,
  390. error_code& ec,
  391. Transform&& transform)
  392. {
  393. static_assert(is_sync_write_stream<SyncWriteStream>::value,
  394. "SyncWriteStream requirements not met");
  395. static_assert(is_sync_read_stream<SyncReadStream>::value,
  396. "SyncReadStream requirements not met");
  397. // A small buffer for relaying the body piece by piece
  398. char buf[2048];
  399. // Create a parser with a buffer body to read from the input.
  400. parser<isRequest, buffer_body> p;
  401. // Create a serializer from the message contained in the parser.
  402. serializer<isRequest, buffer_body, fields> sr{p.get()};
  403. // Read just the header from the input
  404. read_header(input, buffer, p, ec);
  405. if(ec)
  406. return;
  407. // Apply the caller's header transformation
  408. transform(p.get(), ec);
  409. if(ec)
  410. return;
  411. // Send the transformed message to the output
  412. write_header(output, sr, ec);
  413. if(ec)
  414. return;
  415. // Loop over the input and transfer it to the output
  416. do
  417. {
  418. if(! p.is_done())
  419. {
  420. // Set up the body for writing into our small buffer
  421. p.get().body().data = buf;
  422. p.get().body().size = sizeof(buf);
  423. // Read as much as we can
  424. read(input, buffer, p, ec);
  425. // This error is returned when buffer_body uses up the buffer
  426. if(ec == error::need_buffer)
  427. ec = {};
  428. if(ec)
  429. return;
  430. // Set up the body for reading.
  431. // This is how much was parsed:
  432. p.get().body().size = sizeof(buf) - p.get().body().size;
  433. p.get().body().data = buf;
  434. p.get().body().more = ! p.is_done();
  435. }
  436. else
  437. {
  438. p.get().body().data = nullptr;
  439. p.get().body().size = 0;
  440. }
  441. // Write everything in the buffer (which might be empty)
  442. write(output, sr, ec);
  443. // This error is returned when buffer_body uses up the buffer
  444. if(ec == error::need_buffer)
  445. ec = {};
  446. if(ec)
  447. return;
  448. }
  449. while(! p.is_done() && ! sr.is_done());
  450. }
  451. //]
  452. //------------------------------------------------------------------------------
  453. //
  454. // Example: Serialize to std::ostream
  455. //
  456. //------------------------------------------------------------------------------
  457. //[example_http_write_ostream
  458. // The detail namespace means "not public"
  459. namespace detail {
  460. // This helper is needed for C++11.
  461. // When invoked with a buffer sequence, writes the buffers `to the std::ostream`.
  462. template<class Serializer>
  463. class write_ostream_helper
  464. {
  465. Serializer& sr_;
  466. std::ostream& os_;
  467. public:
  468. write_ostream_helper(Serializer& sr, std::ostream& os)
  469. : sr_(sr)
  470. , os_(os)
  471. {
  472. }
  473. // This function is called by the serializer
  474. template<class ConstBufferSequence>
  475. void
  476. operator()(error_code& ec, ConstBufferSequence const& buffers) const
  477. {
  478. // Error codes must be cleared on success
  479. ec = {};
  480. // Keep a running total of how much we wrote
  481. std::size_t bytes_transferred = 0;
  482. // Loop over the buffer sequence
  483. for(auto it = boost::asio::buffer_sequence_begin(buffers);
  484. it != boost::asio::buffer_sequence_end(buffers); ++it)
  485. {
  486. // This is the next buffer in the sequence
  487. boost::asio::const_buffer const buffer = *it;
  488. // Write it to the std::ostream
  489. os_.write(
  490. reinterpret_cast<char const*>(buffer.data()),
  491. buffer.size());
  492. // If the std::ostream fails, convert it to an error code
  493. if(os_.fail())
  494. {
  495. ec = make_error_code(errc::io_error);
  496. return;
  497. }
  498. // Adjust our running total
  499. bytes_transferred += buffer_size(buffer);
  500. }
  501. // Inform the serializer of the amount we consumed
  502. sr_.consume(bytes_transferred);
  503. }
  504. };
  505. } // detail
  506. /** Write a message to a `std::ostream`.
  507. This function writes the serialized representation of the
  508. HTTP/1 message to the sream.
  509. @param os The `std::ostream` to write to.
  510. @param msg The message to serialize.
  511. @param ec Set to the error, if any occurred.
  512. */
  513. template<
  514. bool isRequest,
  515. class Body,
  516. class Fields>
  517. void
  518. write_ostream(
  519. std::ostream& os,
  520. message<isRequest, Body, Fields>& msg,
  521. error_code& ec)
  522. {
  523. // Create the serializer instance
  524. serializer<isRequest, Body, Fields> sr{msg};
  525. // This lambda is used as the "visit" function
  526. detail::write_ostream_helper<decltype(sr)> lambda{sr, os};
  527. do
  528. {
  529. // In C++14 we could use a generic lambda but since we want
  530. // to require only C++11, the lambda is written out by hand.
  531. // This function call retrieves the next serialized buffers.
  532. sr.next(ec, lambda);
  533. if(ec)
  534. return;
  535. }
  536. while(! sr.is_done());
  537. }
  538. //]
  539. //------------------------------------------------------------------------------
  540. //
  541. // Example: Parse from std::istream
  542. //
  543. //------------------------------------------------------------------------------
  544. //[example_http_read_istream
  545. /** Read a message from a `std::istream`.
  546. This function attempts to parse a complete HTTP/1 message from the stream.
  547. @param is The `std::istream` to read from.
  548. @param buffer The buffer to use.
  549. @param msg The message to store the result.
  550. @param ec Set to the error, if any occurred.
  551. */
  552. template<
  553. class Allocator,
  554. bool isRequest,
  555. class Body>
  556. void
  557. read_istream(
  558. std::istream& is,
  559. basic_flat_buffer<Allocator>& buffer,
  560. message<isRequest, Body, fields>& msg,
  561. error_code& ec)
  562. {
  563. // Create the message parser
  564. //
  565. // Arguments passed to the parser's constructor are
  566. // forwarded to the message constructor. Here, we use
  567. // a move construction in case the caller has constructed
  568. // their message in a non-default way.
  569. //
  570. parser<isRequest, Body> p{std::move(msg)};
  571. do
  572. {
  573. // Extract whatever characters are presently available in the istream
  574. if(is.rdbuf()->in_avail() > 0)
  575. {
  576. // Get a mutable buffer sequence for writing
  577. auto const b = buffer.prepare(
  578. static_cast<std::size_t>(is.rdbuf()->in_avail()));
  579. // Now get everything we can from the istream
  580. buffer.commit(static_cast<std::size_t>(is.readsome(
  581. reinterpret_cast<char*>(b.data()), b.size())));
  582. }
  583. else if(buffer.size() == 0)
  584. {
  585. // Our buffer is empty and we need more characters,
  586. // see if we've reached the end of file on the istream
  587. if(! is.eof())
  588. {
  589. // Get a mutable buffer sequence for writing
  590. auto const b = buffer.prepare(1024);
  591. // Try to get more from the istream. This might block.
  592. is.read(reinterpret_cast<char*>(b.data()), b.size());
  593. // If an error occurs on the istream then return it to the caller.
  594. if(is.fail() && ! is.eof())
  595. {
  596. // We'll just re-use io_error since std::istream has no error_code interface.
  597. ec = make_error_code(errc::io_error);
  598. return;
  599. }
  600. // Commit the characters we got to the buffer.
  601. buffer.commit(static_cast<std::size_t>(is.gcount()));
  602. }
  603. else
  604. {
  605. // Inform the parser that we've reached the end of the istream.
  606. p.put_eof(ec);
  607. if(ec)
  608. return;
  609. break;
  610. }
  611. }
  612. // Write the data to the parser
  613. auto const bytes_used = p.put(buffer.data(), ec);
  614. // This error means that the parser needs additional octets.
  615. if(ec == error::need_more)
  616. ec = {};
  617. if(ec)
  618. return;
  619. // Consume the buffer octets that were actually parsed.
  620. buffer.consume(bytes_used);
  621. }
  622. while(! p.is_done());
  623. // Transfer ownership of the message container in the parser to the caller.
  624. msg = p.release();
  625. }
  626. //]
  627. //------------------------------------------------------------------------------
  628. //
  629. // Example: Deferred Body Type
  630. //
  631. //------------------------------------------------------------------------------
  632. //[example_http_defer_body
  633. /** Handle a form POST request, choosing a body type depending on the Content-Type.
  634. This reads a request from the input stream. If the method is POST, and
  635. the Content-Type is "application/x-www-form-urlencoded " or
  636. "multipart/form-data", a `string_body` is used to receive and store
  637. the message body. Otherwise, a `dynamic_body` is used to store the message
  638. body. After the request is received, the handler will be invoked with the
  639. request.
  640. @param stream The stream to read from.
  641. @param buffer The buffer to use for reading.
  642. @param handler The handler to invoke when the request is complete.
  643. The handler must be invokable with this signature:
  644. @code
  645. template<class Body>
  646. void handler(request<Body>&& req);
  647. @endcode
  648. @throws system_error Thrown on failure.
  649. */
  650. template<
  651. class SyncReadStream,
  652. class DynamicBuffer,
  653. class Handler>
  654. void
  655. do_form_request(
  656. SyncReadStream& stream,
  657. DynamicBuffer& buffer,
  658. Handler&& handler)
  659. {
  660. // Start with an empty_body parser
  661. request_parser<empty_body> req0;
  662. // Read just the header. Otherwise, the empty_body
  663. // would generate an error if body octets were received.
  664. read_header(stream, buffer, req0);
  665. // Choose a body depending on the method verb
  666. switch(req0.get().method())
  667. {
  668. case verb::post:
  669. {
  670. // If this is not a form upload then use a string_body
  671. if( req0.get()[field::content_type] != "application/x-www-form-urlencoded" &&
  672. req0.get()[field::content_type] != "multipart/form-data")
  673. goto do_dynamic_body;
  674. // Commit to string_body as the body type.
  675. // As long as there are no body octets in the parser
  676. // we are constructing from, no exception is thrown.
  677. request_parser<string_body> req{std::move(req0)};
  678. // Finish reading the message
  679. read(stream, buffer, req);
  680. // Call the handler. It can take ownership
  681. // if desired, since we are calling release()
  682. handler(req.release());
  683. break;
  684. }
  685. do_dynamic_body:
  686. default:
  687. {
  688. // Commit to dynamic_body as the body type.
  689. // As long as there are no body octets in the parser
  690. // we are constructing from, no exception is thrown.
  691. request_parser<dynamic_body> req{std::move(req0)};
  692. // Finish reading the message
  693. read(stream, buffer, req);
  694. // Call the handler. It can take ownership
  695. // if desired, since we are calling release()
  696. handler(req.release());
  697. break;
  698. }
  699. }
  700. }
  701. //]
  702. //------------------------------------------------------------------------------
  703. //
  704. // Example: Incremental Read
  705. //
  706. //------------------------------------------------------------------------------
  707. //[example_incremental_read
  708. /* This function reads a message using a fixed size buffer to hold
  709. portions of the body, and prints the body contents to a `std::ostream`.
  710. */
  711. template<
  712. bool isRequest,
  713. class SyncReadStream,
  714. class DynamicBuffer>
  715. void
  716. read_and_print_body(
  717. std::ostream& os,
  718. SyncReadStream& stream,
  719. DynamicBuffer& buffer,
  720. error_code& ec)
  721. {
  722. parser<isRequest, buffer_body> p;
  723. read_header(stream, buffer, p, ec);
  724. if(ec)
  725. return;
  726. while(! p.is_done())
  727. {
  728. char buf[512];
  729. p.get().body().data = buf;
  730. p.get().body().size = sizeof(buf);
  731. read(stream, buffer, p, ec);
  732. if(ec == error::need_buffer)
  733. ec = {};
  734. if(ec)
  735. return;
  736. os.write(buf, sizeof(buf) - p.get().body().size);
  737. }
  738. }
  739. //]
  740. //------------------------------------------------------------------------------
  741. //
  742. // Example: Expect 100-continue
  743. //
  744. //------------------------------------------------------------------------------
  745. //[example_chunk_parsing
  746. /** Read a message with a chunked body and print the chunks and extensions
  747. */
  748. template<
  749. bool isRequest,
  750. class SyncReadStream,
  751. class DynamicBuffer>
  752. void
  753. print_chunked_body(
  754. std::ostream& os,
  755. SyncReadStream& stream,
  756. DynamicBuffer& buffer,
  757. error_code& ec)
  758. {
  759. // Declare the parser with an empty body since
  760. // we plan on capturing the chunks ourselves.
  761. parser<isRequest, empty_body> p;
  762. // First read the complete header
  763. read_header(stream, buffer, p, ec);
  764. if(ec)
  765. return;
  766. // This container will hold the extensions for each chunk
  767. chunk_extensions ce;
  768. // This string will hold the body of each chunk
  769. std::string chunk;
  770. // Declare our chunk header callback This is invoked
  771. // after each chunk header and also after the last chunk.
  772. auto header_cb =
  773. [&](std::uint64_t size, // Size of the chunk, or zero for the last chunk
  774. string_view extensions, // The raw chunk-extensions string. Already validated.
  775. error_code& ev) // We can set this to indicate an error
  776. {
  777. // Parse the chunk extensions so we can access them easily
  778. ce.parse(extensions, ev);
  779. if(ev)
  780. return;
  781. // See if the chunk is too big
  782. if(size > (std::numeric_limits<std::size_t>::max)())
  783. {
  784. ev = error::body_limit;
  785. return;
  786. }
  787. // Make sure we have enough storage, and
  788. // reset the container for the upcoming chunk
  789. chunk.reserve(static_cast<std::size_t>(size));
  790. chunk.clear();
  791. };
  792. // Set the callback. The function requires a non-const reference so we
  793. // use a local variable, since temporaries can only bind to const refs.
  794. p.on_chunk_header(header_cb);
  795. // Declare the chunk body callback. This is called one or
  796. // more times for each piece of a chunk body.
  797. auto body_cb =
  798. [&](std::uint64_t remain, // The number of bytes left in this chunk
  799. string_view body, // A buffer holding chunk body data
  800. error_code& ec) // We can set this to indicate an error
  801. {
  802. // If this is the last piece of the chunk body,
  803. // set the error so that the call to `read` returns
  804. // and we can process the chunk.
  805. if(remain == body.size())
  806. ec = error::end_of_chunk;
  807. // Append this piece to our container
  808. chunk.append(body.data(), body.size());
  809. // The return value informs the parser of how much of the body we
  810. // consumed. We will indicate that we consumed everything passed in.
  811. return body.size();
  812. };
  813. p.on_chunk_body(body_cb);
  814. while(! p.is_done())
  815. {
  816. // Read as much as we can. When we reach the end of the chunk, the chunk
  817. // body callback will make the read return with the end_of_chunk error.
  818. read(stream, buffer, p, ec);
  819. if(! ec)
  820. continue;
  821. else if(ec != error::end_of_chunk)
  822. return;
  823. else
  824. ec = {};
  825. // We got a whole chunk, print the extensions:
  826. for(auto const& extension : ce)
  827. {
  828. os << "Extension: " << extension.first;
  829. if(! extension.second.empty())
  830. os << " = " << extension.second << std::endl;
  831. else
  832. os << std::endl;
  833. }
  834. // Now print the chunk body
  835. os << "Chunk Body: " << chunk << std::endl;
  836. }
  837. // Get a reference to the parsed message, this is for convenience
  838. auto const& msg = p.get();
  839. // Check each field promised in the "Trailer" header and output it
  840. for(auto const& name : token_list{msg[field::trailer]})
  841. {
  842. // Find the trailer field
  843. auto it = msg.find(name);
  844. if(it == msg.end())
  845. {
  846. // Oops! They promised the field but failed to deliver it
  847. os << "Missing Trailer: " << name << std::endl;
  848. continue;
  849. }
  850. os << it->name() << ": " << it->value() << std::endl;
  851. }
  852. }
  853. //]
  854. } // http
  855. } // beast
  856. } // boost