| 103 | // request), is type-erased in message_generator. |
| 104 | template <class Body, class Allocator> |
| 105 | http::message_generator |
| 106 | handle_request( |
| 107 | beast::string_view doc_root, |
| 108 | http::request<Body, http::basic_fields<Allocator>>&& req) |
| 109 | { |
| 110 | // Returns a bad request response |
| 111 | auto const bad_request = |
| 112 | [&req](beast::string_view why) |
| 113 | { |
| 114 | http::response<http::string_body> res{http::status::bad_request, req.version()}; |
| 115 | res.set(http::field::server, BOOST_BEAST_VERSION_STRING); |
| 116 | res.set(http::field::content_type, "text/html"); |
| 117 | res.keep_alive(req.keep_alive()); |
| 118 | res.body() = std::string(why); |
| 119 | res.prepare_payload(); |
| 120 | return res; |
| 121 | }; |
| 122 | |
| 123 | // Returns a not found response |
| 124 | auto const not_found = |
| 125 | [&req](beast::string_view target) |
| 126 | { |
| 127 | http::response<http::string_body> res{http::status::not_found, req.version()}; |
| 128 | res.set(http::field::server, BOOST_BEAST_VERSION_STRING); |
| 129 | res.set(http::field::content_type, "text/html"); |
| 130 | res.keep_alive(req.keep_alive()); |
| 131 | res.body() = "The resource '" + std::string(target) + "' was not found."; |
| 132 | res.prepare_payload(); |
| 133 | return res; |
| 134 | }; |
| 135 | |
| 136 | // Returns a server error response |
| 137 | auto const server_error = |
| 138 | [&req](beast::string_view what) |
| 139 | { |
| 140 | http::response<http::string_body> res{http::status::internal_server_error, req.version()}; |
| 141 | res.set(http::field::server, BOOST_BEAST_VERSION_STRING); |
| 142 | res.set(http::field::content_type, "text/html"); |
| 143 | res.keep_alive(req.keep_alive()); |
| 144 | res.body() = "An error occurred: '" + std::string(what) + "'"; |
| 145 | res.prepare_payload(); |
| 146 | return res; |
| 147 | }; |
| 148 | |
| 149 | // Make sure we can handle the method |
| 150 | if( req.method() != http::verb::get && |
| 151 | req.method() != http::verb::head) |
| 152 | return bad_request("Unknown HTTP-method"); |
| 153 | |
| 154 | // Request path must be absolute and not contain "..". |
| 155 | if( req.target().empty() || |
| 156 | req.target()[0] != '/' || |
| 157 | req.target().find("..") != beast::string_view::npos) |
| 158 | return bad_request("Illegal request-target"); |
| 159 | |
| 160 | // Build the path to the requested file |
| 161 | std::string path = path_cat(doc_root, req.target()); |
| 162 | if(req.target().back() == '/') |
no test coverage detected