1 #include <iostream>
2
3 #include <restinio/all.hpp>
4
5 template < typename RESP >
6 RESP
init_resp(RESP resp)7 init_resp( RESP resp )
8 {
9 resp.append_header( restinio::http_field::server, "RESTinio sample server /v.0.2" );
10 resp.append_header_date_field();
11
12 return resp;
13 }
14
15 using router_t = restinio::router::express_router_t<>;
16
create_request_handler()17 auto create_request_handler()
18 {
19 auto router = std::make_unique< router_t >();
20
21 router->http_get(
22 "/",
23 []( auto req, auto ){
24 init_resp( req->create_response() )
25 .append_header( restinio::http_field::content_type, "text/plain; charset=utf-8" )
26 .set_body( "Hello world!")
27 .done();
28
29 return restinio::request_accepted();
30 } );
31
32 router->http_get(
33 "/json",
34 []( auto req, auto ){
35 init_resp( req->create_response() )
36 .append_header( restinio::http_field::content_type, "application/json" )
37 .set_body( R"-({"message" : "Hello world!"})-")
38 .done();
39
40 return restinio::request_accepted();
41 } );
42
43 router->http_get(
44 "/html",
45 []( auto req, auto ){
46 init_resp( req->create_response() )
47 .append_header( restinio::http_field::content_type, "text/html; charset=utf-8" )
48 .set_body(
49 "<html>\r\n"
50 " <head><title>Hello from RESTinio!</title></head>\r\n"
51 " <body>\r\n"
52 " <center><h1>Hello world</h1></center>\r\n"
53 " </body>\r\n"
54 "</html>\r\n" )
55 .done();
56
57 return restinio::request_accepted();
58 } );
59
60 return router;
61 }
62
main()63 int main()
64 {
65 using namespace std::chrono;
66
67 try
68 {
69 using traits_t =
70 restinio::traits_t<
71 restinio::asio_timer_manager_t,
72 restinio::single_threaded_ostream_logger_t,
73 router_t >;
74
75 restinio::run(
76 restinio::on_this_thread<traits_t>()
77 .port( 8080 )
78 .address( "localhost" )
79 .request_handler( create_request_handler() ) );
80 }
81 catch( const std::exception & ex )
82 {
83 std::cerr << "Error: " << ex.what() << std::endl;
84 return 1;
85 }
86
87 return 0;
88 }
89