2 // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
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)
7 // Official repository: https://github.com/boostorg/beast
10 //------------------------------------------------------------------------------
12 // Example: HTTP server, coroutine
14 //------------------------------------------------------------------------------
16 #include <boost/beast/core.hpp>
17 #include <boost/beast/http.hpp>
18 #include <boost/beast/version.hpp>
19 #include <boost/asio/ip/tcp.hpp>
20 #include <boost/asio/spawn.hpp>
21 #include <boost/config.hpp>
30 using tcp
= boost::asio::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
31 namespace http
= boost::beast::http
; // from <boost/beast/http.hpp>
33 // Return a reasonable mime type based on the extension of a file.
34 boost::beast::string_view
35 mime_type(boost::beast::string_view path
)
37 using boost::beast::iequals
;
38 auto const ext
= [&path
]
40 auto const pos
= path
.rfind(".");
41 if(pos
== boost::beast::string_view::npos
)
42 return boost::beast::string_view
{};
43 return path
.substr(pos
);
45 if(iequals(ext
, ".htm")) return "text/html";
46 if(iequals(ext
, ".html")) return "text/html";
47 if(iequals(ext
, ".php")) return "text/html";
48 if(iequals(ext
, ".css")) return "text/css";
49 if(iequals(ext
, ".txt")) return "text/plain";
50 if(iequals(ext
, ".js")) return "application/javascript";
51 if(iequals(ext
, ".json")) return "application/json";
52 if(iequals(ext
, ".xml")) return "application/xml";
53 if(iequals(ext
, ".swf")) return "application/x-shockwave-flash";
54 if(iequals(ext
, ".flv")) return "video/x-flv";
55 if(iequals(ext
, ".png")) return "image/png";
56 if(iequals(ext
, ".jpe")) return "image/jpeg";
57 if(iequals(ext
, ".jpeg")) return "image/jpeg";
58 if(iequals(ext
, ".jpg")) return "image/jpeg";
59 if(iequals(ext
, ".gif")) return "image/gif";
60 if(iequals(ext
, ".bmp")) return "image/bmp";
61 if(iequals(ext
, ".ico")) return "image/vnd.microsoft.icon";
62 if(iequals(ext
, ".tiff")) return "image/tiff";
63 if(iequals(ext
, ".tif")) return "image/tiff";
64 if(iequals(ext
, ".svg")) return "image/svg+xml";
65 if(iequals(ext
, ".svgz")) return "image/svg+xml";
66 return "application/text";
69 // Append an HTTP rel-path to a local filesystem path.
70 // The returned path is normalized for the platform.
73 boost::beast::string_view base
,
74 boost::beast::string_view path
)
77 return path
.to_string();
78 std::string result
= base
.to_string();
80 char constexpr path_separator
= '\\';
81 if(result
.back() == path_separator
)
82 result
.resize(result
.size() - 1);
83 result
.append(path
.data(), path
.size());
88 char constexpr path_separator
= '/';
89 if(result
.back() == path_separator
)
90 result
.resize(result
.size() - 1);
91 result
.append(path
.data(), path
.size());
96 // This function produces an HTTP response for the given
97 // request. The type of the response object depends on the
98 // contents of the request, so the interface requires the
99 // caller to pass a generic lambda for receiving the response.
101 class Body
, class Allocator
,
105 boost::beast::string_view doc_root
,
106 http::request
<Body
, http::basic_fields
<Allocator
>>&& req
,
109 // Returns a bad request response
110 auto const bad_request
=
111 [&req
](boost::beast::string_view why
)
113 http::response
<http::string_body
> res
{http::status::bad_request
, req
.version()};
114 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
115 res
.set(http::field::content_type
, "text/html");
116 res
.keep_alive(req
.keep_alive());
117 res
.body() = why
.to_string();
118 res
.prepare_payload();
122 // Returns a not found response
123 auto const not_found
=
124 [&req
](boost::beast::string_view target
)
126 http::response
<http::string_body
> res
{http::status::not_found
, req
.version()};
127 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
128 res
.set(http::field::content_type
, "text/html");
129 res
.keep_alive(req
.keep_alive());
130 res
.body() = "The resource '" + target
.to_string() + "' was not found.";
131 res
.prepare_payload();
135 // Returns a server error response
136 auto const server_error
=
137 [&req
](boost::beast::string_view what
)
139 http::response
<http::string_body
> res
{http::status::internal_server_error
, req
.version()};
140 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
141 res
.set(http::field::content_type
, "text/html");
142 res
.keep_alive(req
.keep_alive());
143 res
.body() = "An error occurred: '" + what
.to_string() + "'";
144 res
.prepare_payload();
148 // Make sure we can handle the method
149 if( req
.method() != http::verb::get
&&
150 req
.method() != http::verb::head
)
151 return send(bad_request("Unknown HTTP-method"));
153 // Request path must be absolute and not contain "..".
154 if( req
.target().empty() ||
155 req
.target()[0] != '/' ||
156 req
.target().find("..") != boost::beast::string_view::npos
)
157 return send(bad_request("Illegal request-target"));
159 // Build the path to the requested file
160 std::string path
= path_cat(doc_root
, req
.target());
161 if(req
.target().back() == '/')
162 path
.append("index.html");
164 // Attempt to open the file
165 boost::beast::error_code ec
;
166 http::file_body::value_type body
;
167 body
.open(path
.c_str(), boost::beast::file_mode::scan
, ec
);
169 // Handle the case where the file doesn't exist
170 if(ec
== boost::system::errc::no_such_file_or_directory
)
171 return send(not_found(req
.target()));
173 // Handle an unknown error
175 return send(server_error(ec
.message()));
177 // Respond to HEAD request
178 if(req
.method() == http::verb::head
)
180 http::response
<http::empty_body
> res
{http::status::ok
, req
.version()};
181 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
182 res
.set(http::field::content_type
, mime_type(path
));
183 res
.content_length(body
.size());
184 res
.keep_alive(req
.keep_alive());
185 return send(std::move(res
));
188 // Respond to GET request
189 http::response
<http::file_body
> res
{
190 std::piecewise_construct
,
191 std::make_tuple(std::move(body
)),
192 std::make_tuple(http::status::ok
, req
.version())};
193 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
194 res
.set(http::field::content_type
, mime_type(path
));
195 res
.content_length(body
.size());
196 res
.keep_alive(req
.keep_alive());
197 return send(std::move(res
));
200 //------------------------------------------------------------------------------
204 fail(boost::system::error_code ec
, char const* what
)
206 std::cerr
<< what
<< ": " << ec
.message() << "\n";
209 // This is the C++11 equivalent of a generic lambda.
210 // The function object is used to send an HTTP message.
211 template<class Stream
>
216 boost::system::error_code
& ec_
;
217 boost::asio::yield_context yield_
;
223 boost::system::error_code
& ec
,
224 boost::asio::yield_context yield
)
232 template<bool isRequest
, class Body
, class Fields
>
234 operator()(http::message
<isRequest
, Body
, Fields
>&& msg
) const
236 // Determine if we should close the connection after
237 close_
= msg
.need_eof();
239 // We need the serializer here because the serializer requires
240 // a non-const file_body, and the message oriented version of
241 // http::write only works with const messages.
242 http::serializer
<isRequest
, Body
, Fields
> sr
{msg
};
243 http::async_write(stream_
, sr
, yield_
[ec_
]);
247 // Handles an HTTP server connection
251 std::string
const& doc_root
,
252 boost::asio::yield_context yield
)
255 boost::system::error_code ec
;
257 // This buffer is required to persist across reads
258 boost::beast::flat_buffer buffer
;
260 // This lambda is used to send messages
261 send_lambda
<tcp::socket
> lambda
{socket
, close
, ec
, yield
};
266 http::request
<http::string_body
> req
;
267 http::async_read(socket
, buffer
, req
, yield
[ec
]);
268 if(ec
== http::error::end_of_stream
)
271 return fail(ec
, "read");
274 handle_request(doc_root
, std::move(req
), lambda
);
276 return fail(ec
, "write");
279 // This means we should close the connection, usually because
280 // the response indicated the "Connection: close" semantic.
285 // Send a TCP shutdown
286 socket
.shutdown(tcp::socket::shutdown_send
, ec
);
288 // At this point the connection is closed gracefully
291 //------------------------------------------------------------------------------
293 // Accepts incoming connections and launches the sessions
296 boost::asio::io_context
& ioc
,
297 tcp::endpoint endpoint
,
298 std::string
const& doc_root
,
299 boost::asio::yield_context yield
)
301 boost::system::error_code ec
;
304 tcp::acceptor
acceptor(ioc
);
305 acceptor
.open(endpoint
.protocol(), ec
);
307 return fail(ec
, "open");
309 // Bind to the server address
310 acceptor
.bind(endpoint
, ec
);
312 return fail(ec
, "bind");
314 // Start listening for connections
315 acceptor
.listen(boost::asio::socket_base::max_listen_connections
, ec
);
317 return fail(ec
, "listen");
321 tcp::socket
socket(ioc
);
322 acceptor
.async_accept(socket
, yield
[ec
]);
327 acceptor
.get_executor().context(),
332 std::placeholders::_1
));
336 int main(int argc
, char* argv
[])
338 // Check command line arguments.
342 "Usage: http-server-coro <address> <port> <doc_root> <threads>\n" <<
344 " http-server-coro 0.0.0.0 8080 . 1\n";
347 auto const address
= boost::asio::ip::make_address(argv
[1]);
348 auto const port
= static_cast<unsigned short>(std::atoi(argv
[2]));
349 std::string
const doc_root
= argv
[3];
350 auto const threads
= std::max
<int>(1, std::atoi(argv
[4]));
352 // The io_context is required for all I/O
353 boost::asio::io_context ioc
{threads
};
355 // Spawn a listening port
356 boost::asio::spawn(ioc
,
360 tcp::endpoint
{address
, port
},
362 std::placeholders::_1
));
364 // Run the I/O service on the requested number of threads
365 std::vector
<std::thread
> v
;
366 v
.reserve(threads
- 1);
367 for(auto i
= threads
- 1; i
> 0; --i
)