Using restinio::run
The simplest way of running RESTinio server is the usage of restinio::run
functions. For example, to run single-threaded RESTinio server on the
context of the current thread:
restinio::run(
restinio::on_this_thread()
.port(8080)
.address("localhost")
.request_handler([](auto req) {
return req->create_response().set_body("Hello, World!").done();
}));
// The current thread will be blocked until RESTinio server finishes its work.
To run multi-threaded RESTinio server on the context of thread pool:
restinio::run(
restinio::on_thread_pool(16) // Thread pool size is 16 threads.
.port(8080)
.address("localhost")
.request_handler([](auto req) {
return req->create_response().set_body("Hello, World!").done();
}));
// The current thread will be blocked until RESTinio server finishes its work.
Note that run()
doesn’t provide a way to stop the server from outside of
run()
. It means that run()
will block the current thread until the
server will finish its work by itself. However inside run()
a signal
handler for SIGINT it installed and the server finishes its work when SIGINT is
sent to the application (for example if the user breaks the application by pressing
Ctrl+C/Ctrl+Break). Such approach seems to be appropriate for very simple
servers like small test programs or quick-and-dirty prototypes. If you need
more control you should use restinio::http_server_t
class.
A user-defined traits for RESTinio server can be passed as template parameters
for restinio::on_this_thread
and restinio::on_thread_pool
helpers.
For example:
using my_traits_t = restinio::traits_t<
restinio::asio_timer_manager_t,
restinio::single_threaded_ostream_logger_t,
restinio::router::express_router_t >;
restinio::run(
restinio::on_this_thread<my_traits_t>()
.port(8080)
.address("localhost")
.request_handler([](auto req) {
return req->create_response().set_body("Hello, World!").done();
}));
// The current thread will be blocked until RESTinio server finishes its work.