| 83 | // request), is type-erased in message_generator. |
| 84 | template <class Body, class Allocator> |
| 85 | http::message_generator |
| 86 | handle_request( |
| 87 | beast::string_view doc_root, |
| 88 | http::request<Body, http::basic_fields<Allocator>>&& req) |
| 89 | { |
| 90 | // Returns a bad request response |
| 91 | auto const bad_request = |
| 92 | [&req](beast::string_view why) |
| 93 | { |
| 94 | http::response<http::string_body> res{http::status::bad_request, req.version()}; |
| 95 | res.set(http::field::server, BOOST_BEAST_VERSION_STRING); |
| 96 | res.set(http::field::content_type, "text/html"); |
| 97 | res.keep_alive(req.keep_alive()); |
| 98 | res.body() = std::string(why); |
| 99 | res.prepare_payload(); |
| 100 | return res; |
| 101 | }; |
| 102 | |
| 103 | // Returns a not found response |
| 104 | auto const not_found = |
| 105 | [&req](beast::string_view target) |
| 106 | { |
| 107 | http::response<http::string_body> res{http::status::not_found, req.version()}; |
| 108 | res.set(http::field::server, BOOST_BEAST_VERSION_STRING); |
| 109 | res.set(http::field::content_type, "text/html"); |
| 110 | res.keep_alive(req.keep_alive()); |
| 111 | res.body() = "The resource '" + std::string(target) + "' was not found."; |
| 112 | res.prepare_payload(); |
| 113 | return res; |
| 114 | }; |
| 115 | |
| 116 | // Returns a server error response |
| 117 | auto const server_error = |
| 118 | [&req](beast::string_view what) |
| 119 | { |
| 120 | http::response<http::string_body> res{http::status::internal_server_error, req.version()}; |
| 121 | res.set(http::field::server, BOOST_BEAST_VERSION_STRING); |
| 122 | res.set(http::field::content_type, "text/html"); |
| 123 | res.keep_alive(req.keep_alive()); |
| 124 | res.body() = "An error occurred: '" + std::string(what) + "'"; |
| 125 | res.prepare_payload(); |
| 126 | return res; |
| 127 | }; |
| 128 | |
| 129 | // Make sure we can handle the method |
| 130 | if( req.method() != http::verb::get && |
| 131 | req.method() != http::verb::head) |
| 132 | return bad_request("Unknown HTTP-method"); |
| 133 | |
| 134 | // Request path must be absolute and not contain "..". |
| 135 | if( req.target().empty() || |
| 136 | req.target()[0] != '/' || |
| 137 | req.target().find("..") != beast::string_view::npos) |
| 138 | return bad_request("Illegal request-target"); |
| 139 | |
| 140 | // Build the path to the requested file |
| 141 | std::string path = path_cat(doc_root, req.target()); |
| 142 | if(req.target().back() == '/') |
no test coverage detected