1+ // Server libs
2+ #include < nghttp2/asio_http2_server.h>
3+
4+ // Standard libs
5+ #include < fstream>
6+ #include < iostream>
7+
8+ #include < chrono>
9+ #include < sys/time.h>
10+ #include < ctime>
11+
12+ #include < thread>
13+
14+ // namespaces
15+ using namespace nghttp2 ::asio_http2;
16+ using namespace nghttp2 ::asio_http2::server;
17+
18+ namespace ba = boost::asio;
19+ namespace
20+ {
21+ // server push demonstration constants
22+ static const auto html = R"(
23+ <!DOCTYPE html>
24+ <html lang="en">
25+ <title>HTTP/2 FTW</title>
26+ <body>
27+ <link href="/style.css" rel="stylesheet" type="text/css">
28+ <h1>This should be green</h1>
29+ </body>
30+ </html>\n)" ;
31+
32+ static const auto css = " h1 { color: green; }" ;
33+
34+ }
35+
36+ int main (int argc, char *argv[]) {
37+ boost::system::error_code ec;
38+ http2 server;
39+
40+ // Concurrency
41+ // unsigned int cores = std::thread::hardware_concurrency();
42+ // server.num_threads((cores?cores:1));
43+
44+ // Server push resource
45+ server.handle (" /serverpush" , [](const request &req, const response &res) {
46+ std::cout << " Got a /serverpush request!" << std::endl;
47+ boost::system::error_code ec;
48+ auto push = res.push (ec, " GET" , " /style.css" );
49+ push->write_head (200 );
50+ push->end (css);
51+ res.write_head (200 );
52+ res.end (html);
53+ });
54+
55+ // Normal application/json resource
56+ server.handle (" /" , [](const request &req, const response &res) {
57+ std::cout << " Got a / request!" << std::endl;
58+ nghttp2::asio_http2::header_map headers;
59+ headers.insert (
60+ std::make_pair<std::string, nghttp2::asio_http2::header_value>(
61+ " content-type" ,
62+ {" application/json; charset=utf-8" ,false }));
63+ res.write_head (200 ,headers);
64+ res.end (" {\" SERVER\" :\" UP\" }\n " );
65+ });
66+
67+ // TLS context for HTTP/2
68+ boost::asio::ssl::context tlsCtx (boost::asio::ssl::context::sslv23);
69+ tlsCtx.use_private_key_file (" /usr/local/share/ca-certificates/cpphttp2server.key" ,
70+ boost::asio::ssl::context::pem);
71+ tlsCtx.use_certificate_chain_file (" /usr/local/share/ca-certificates/cpphttp2server.crt" );
72+ configure_tls_context_easy (ec, tlsCtx);
73+
74+ std::cout << " STARTING HTTP/2 CPP server!" << std::endl;
75+ // std::cout << "STARTING HTTP/2 CPP server WITH " << cores << " concurrent threads!" << std::endl;
76+ if (server.listen_and_serve (ec,tlsCtx, " 0.0.0.0" , " 3000" )) {
77+ std::cerr << " error: " << ec.message () << std::endl;
78+ }
79+
80+ }
0 commit comments