diff --git a/client_http.hpp b/client_http.hpp index 10846b1..964bdef 100644 --- a/client_http.hpp +++ b/client_http.hpp @@ -134,7 +134,7 @@ namespace SimpleWeb { void close() { error_code ec; - std::unique_lock lock(socket_close_mutex); // the following operations seems to be needed to run sequentially + std::unique_lock lock(socket_close_mutex); // The following operations seems to be needed to run sequentially socket->lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, ec); socket->lowest_layer().close(ec); } @@ -586,7 +586,7 @@ namespace SimpleWeb { tmp_stream.write(&buffer[0], length); } - //Remove "\r\n" + // Remove "\r\n" session->response->content.get(); session->response->content.get(); diff --git a/http_examples.cpp b/http_examples.cpp index 2bfe754..87234e3 100644 --- a/http_examples.cpp +++ b/http_examples.cpp @@ -1,12 +1,12 @@ #include "client_http.hpp" #include "server_http.hpp" -//Added for the json-example +// Added for the json-example #define BOOST_SPIRIT_THREADSAFE #include #include -//Added for the default_resource example +// Added for the default_resource example #include #include #include @@ -16,28 +16,28 @@ #endif using namespace std; -//Added for the json-example: +// Added for the json-example: using namespace boost::property_tree; typedef SimpleWeb::Server HttpServer; typedef SimpleWeb::Client HttpClient; int main() { - //HTTP-server at port 8080 using 1 thread - //Unless you do more heavy non-threaded processing in the resources, - //1 thread is usually faster than several threads + // HTTP-server at port 8080 using 1 thread + // Unless you do more heavy non-threaded processing in the resources, + // 1 thread is usually faster than several threads HttpServer server; server.config.port = 8080; - //Add resources using path-regex and method-string, and an anonymous function - //POST-example for the path /string, responds the posted string + // Add resources using path-regex and method-string, and an anonymous function + // POST-example for the path /string, responds the posted string server.resource["^/string$"]["POST"] = [](shared_ptr response, shared_ptr request) { - //Retrieve string: + // Retrieve string: auto content = request->content.string(); - //request->content.string() is a convenience function for: - //stringstream ss; - //ss << request->content.rdbuf(); - //auto content=ss.str(); + // request->content.string() is a convenience function for: + // stringstream ss; + // ss << request->content.rdbuf(); + // auto content=ss.str(); *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content; @@ -47,14 +47,14 @@ int main() { // response->write(content); }; - //POST-example for the path /json, responds firstName+" "+lastName from the posted json - //Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing - //Example posted json: - //{ - // "firstName": "John", - // "lastName": "Smith", - // "age": 25 - //} + // POST-example for the path /json, responds firstName+" "+lastName from the posted json + // Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing + // Example posted json: + // { + // "firstName": "John", + // "lastName": "Smith", + // "age": 25 + // } server.resource["^/json$"]["POST"] = [](shared_ptr response, shared_ptr request) { try { ptree pt; @@ -85,8 +85,8 @@ int main() { // } }; - //GET-example for the path /info - //Responds with request-information + // GET-example for the path /info + // Responds with request-information server.resource["^/info$"]["GET"] = [](shared_ptr response, shared_ptr request) { stringstream stream; stream << "

Request from " << request->remote_endpoint_address << " (" << request->remote_endpoint_port << ")

"; @@ -94,7 +94,7 @@ int main() { for(auto &header : request->header) stream << header.first << ": " << header.second << "
"; - //find length of content_stream (length received using content_stream.tellp()) + // Find length of content_stream (length received using content_stream.tellp()) stream.seekp(0, ios::end); *response << "HTTP/1.1 200 OK\r\nContent-Length: " << stream.tellp() << "\r\n\r\n" @@ -110,8 +110,8 @@ int main() { // response->write(stream); }; - //GET-example for the path /match/[number], responds with the matched string in path (number) - //For instance a request GET /match/123 will receive: 123 + // GET-example for the path /match/[number], responds with the matched string in path (number) + // For instance a request GET /match/123 will receive: 123 server.resource["^/match/([0-9]+)$"]["GET"] = [](shared_ptr response, shared_ptr request) { string number = request->path_match[1]; *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" @@ -122,7 +122,7 @@ int main() { // response->write(request->path_match[1]); }; - //Get example simulating heavy work in a separate thread + // Get example simulating heavy work in a separate thread server.resource["^/work$"]["GET"] = [](shared_ptr response, shared_ptr /*request*/) { thread work_thread([response] { this_thread::sleep_for(chrono::seconds(5)); @@ -131,15 +131,15 @@ int main() { work_thread.detach(); }; - //Default GET-example. If no other matches, this anonymous function will be called. - //Will respond with content in the web/-directory, and its subdirectories. - //Default file: index.html - //Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server + // Default GET-example. If no other matches, this anonymous function will be called. + // Will respond with content in the web/-directory, and its subdirectories. + // Default file: index.html + // Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server server.default_resource["GET"] = [](shared_ptr response, shared_ptr request) { try { auto web_root_path = boost::filesystem::canonical("web"); auto path = boost::filesystem::canonical(web_root_path / request->path); - //Check if path is within web_root_path + // Check if path is within web_root_path if(distance(web_root_path.begin(), web_root_path.end()) > distance(path.begin(), path.end()) || !equal(web_root_path.begin(), web_root_path.end(), path.begin())) throw invalid_argument("path must be within root path"); @@ -181,10 +181,11 @@ int main() { header.emplace("Content-Length", to_string(length)); response->write(header); + // Trick to define a recursive function within this scope (for your convenience) class FileServer { public: static void read_and_send(const shared_ptr &response, const shared_ptr &ifs) { - //read and send 128 KB at a time + // Read and send 128 KB at a time static vector buffer(131072); // Safe when server is running on one thread streamsize read_length; if((read_length = ifs->read(&buffer[0], buffer.size()).gcount()) > 0) { @@ -211,21 +212,21 @@ int main() { }; server.on_error = [](shared_ptr /*request*/, const SimpleWeb::error_code & /*ec*/) { - // handle errors here + // Handle errors here }; thread server_thread([&server]() { - //Start server + // Start server server.start(); }); - //Wait for server to start so that the client can connect + // Wait for server to start so that the client can connect this_thread::sleep_for(chrono::seconds(1)); - //Client examples + // Client examples HttpClient client("localhost:8080"); - // synchronous request examples + // Synchronous request examples auto r1 = client.request("GET", "/match/123"); cout << r1->content.rdbuf() << endl; // Alternatively, use the convenience function r1->content.string() @@ -233,7 +234,7 @@ int main() { auto r2 = client.request("POST", "/string", json_string); cout << r2->content.rdbuf() << endl; - // asynchronous request example + // Asynchronous request example client.request("POST", "/json", json_string, [](shared_ptr response, const SimpleWeb::error_code &ec) { if(!ec) cout << response->content.rdbuf() << endl; diff --git a/https_examples.cpp b/https_examples.cpp index 886b51a..85d4184 100644 --- a/https_examples.cpp +++ b/https_examples.cpp @@ -1,12 +1,12 @@ #include "client_https.hpp" #include "server_https.hpp" -//Added for the json-example +// Added for the json-example #define BOOST_SPIRIT_THREADSAFE #include #include -//Added for the default_resource example +// Added for the default_resource example #include "crypto.hpp" #include #include @@ -14,28 +14,28 @@ #include using namespace std; -//Added for the json-example: +// Added for the json-example: using namespace boost::property_tree; typedef SimpleWeb::Server HttpsServer; typedef SimpleWeb::Client HttpsClient; int main() { - //HTTPS-server at port 8080 using 1 thread - //Unless you do more heavy non-threaded processing in the resources, - //1 thread is usually faster than several threads + // HTTPS-server at port 8080 using 1 thread + // Unless you do more heavy non-threaded processing in the resources, + // 1 thread is usually faster than several threads HttpsServer server("server.crt", "server.key"); server.config.port = 8080; - //Add resources using path-regex and method-string, and an anonymous function - //POST-example for the path /string, responds the posted string + // Add resources using path-regex and method-string, and an anonymous function + // POST-example for the path /string, responds the posted string server.resource["^/string$"]["POST"] = [](shared_ptr response, shared_ptr request) { - //Retrieve string: + // Retrieve string: auto content = request->content.string(); - //request->content.string() is a convenience function for: - //stringstream ss; - //ss << request->content.rdbuf(); - //auto content=ss.str(); + // request->content.string() is a convenience function for: + // stringstream ss; + // ss << request->content.rdbuf(); + // auto content=ss.str(); *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content; @@ -45,14 +45,14 @@ int main() { // response->write(content); }; - //POST-example for the path /json, responds firstName+" "+lastName from the posted json - //Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing - //Example posted json: - //{ - // "firstName": "John", - // "lastName": "Smith", - // "age": 25 - //} + // POST-example for the path /json, responds firstName+" "+lastName from the posted json + // Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing + // Example posted json: + // { + // "firstName": "John", + // "lastName": "Smith", + // "age": 25 + // } server.resource["^/json$"]["POST"] = [](shared_ptr response, shared_ptr request) { try { ptree pt; @@ -83,8 +83,8 @@ int main() { // } }; - //GET-example for the path /info - //Responds with request-information + // GET-example for the path /info + // Responds with request-information server.resource["^/info$"]["GET"] = [](shared_ptr response, shared_ptr request) { stringstream stream; stream << "

Request from " << request->remote_endpoint_address << " (" << request->remote_endpoint_port << ")

"; @@ -92,7 +92,7 @@ int main() { for(auto &header : request->header) stream << header.first << ": " << header.second << "
"; - //find length of content_stream (length received using content_stream.tellp()) + // Find length of content_stream (length received using content_stream.tellp()) stream.seekp(0, ios::end); *response << "HTTP/1.1 200 OK\r\nContent-Length: " << stream.tellp() << "\r\n\r\n" @@ -108,8 +108,8 @@ int main() { // response->write(stream); }; - //GET-example for the path /match/[number], responds with the matched string in path (number) - //For instance a request GET /match/123 will receive: 123 + // GET-example for the path /match/[number], responds with the matched string in path (number) + // For instance a request GET /match/123 will receive: 123 server.resource["^/match/([0-9]+)$"]["GET"] = [](shared_ptr response, shared_ptr request) { string number = request->path_match[1]; *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" @@ -120,7 +120,7 @@ int main() { // response->write(request->path_match[1]); }; - //Get example simulating heavy work in a separate thread + // Get example simulating heavy work in a separate thread server.resource["^/work$"]["GET"] = [](shared_ptr response, shared_ptr /*request*/) { thread work_thread([response] { this_thread::sleep_for(chrono::seconds(5)); @@ -129,15 +129,15 @@ int main() { work_thread.detach(); }; - //Default GET-example. If no other matches, this anonymous function will be called. - //Will respond with content in the web/-directory, and its subdirectories. - //Default file: index.html - //Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server + // Default GET-example. If no other matches, this anonymous function will be called. + // Will respond with content in the web/-directory, and its subdirectories. + // Default file: index.html + // Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server server.default_resource["GET"] = [](shared_ptr response, shared_ptr request) { try { auto web_root_path = boost::filesystem::canonical("web"); auto path = boost::filesystem::canonical(web_root_path / request->path); - //Check if path is within web_root_path + // Check if path is within web_root_path if(distance(web_root_path.begin(), web_root_path.end()) > distance(path.begin(), path.end()) || !equal(web_root_path.begin(), web_root_path.end(), path.begin())) throw invalid_argument("path must be within root path"); @@ -179,10 +179,11 @@ int main() { header.emplace("Content-Length", to_string(length)); response->write(header); + // Trick to define a recursive function within this scope (for your convenience) class FileServer { public: static void read_and_send(const shared_ptr &response, const shared_ptr &ifs) { - //read and send 128 KB at a time + // Read and send 128 KB at a time static vector buffer(131072); // Safe when server is running on one thread streamsize read_length; if((read_length = ifs->read(&buffer[0], buffer.size()).gcount()) > 0) { @@ -209,22 +210,22 @@ int main() { }; server.on_error = [](shared_ptr /*request*/, const SimpleWeb::error_code & /*ec*/) { - // handle errors here + // Handle errors here }; thread server_thread([&server]() { - //Start server + // Start server server.start(); }); - //Wait for server to start so that the client can connect + // Wait for server to start so that the client can connect this_thread::sleep_for(chrono::seconds(1)); - //Client examples - //Second create() parameter set to false: no certificate verification + // Client examples + // Second create() parameter set to false: no certificate verification HttpsClient client("localhost:8080", false); - // synchronous request examples + // Synchronous request examples auto r1 = client.request("GET", "/match/123"); cout << r1->content.rdbuf() << endl; // Alternatively, use the convenience function r1->content.string() @@ -232,7 +233,7 @@ int main() { auto r2 = client.request("POST", "/string", json_string); cout << r2->content.rdbuf() << endl; - // asynchronous request example + // Asynchronous request example client.request("POST", "/json", json_string, [](shared_ptr response, const SimpleWeb::error_code &ec) { if(!ec) cout << response->content.rdbuf() << endl; diff --git a/server_http.hpp b/server_http.hpp index 9560210..3658bc2 100644 --- a/server_http.hpp +++ b/server_http.hpp @@ -271,7 +271,7 @@ namespace SimpleWeb { void close() { error_code ec; - std::unique_lock lock(socket_close_mutex); // the following operations seems to be needed to run sequentially + std::unique_lock lock(socket_close_mutex); // The following operations seems to be needed to run sequentially socket->lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, ec); socket->lowest_layer().close(ec); } @@ -342,7 +342,7 @@ namespace SimpleWeb { /// Set to false to avoid binding the socket to an address that is already in use. Defaults to true. bool reuse_address = true; }; - ///Set before calling start(). + /// Set before calling start(). Config config; private: @@ -397,7 +397,7 @@ namespace SimpleWeb { accept(); if(internal_io_service) { - //If thread_pool_size>1, start m_io_service.run() in (thread_pool_size-1) threads for thread-pooling + // If thread_pool_size>1, start m_io_service.run() in (thread_pool_size-1) threads for thread-pooling threads.clear(); for(size_t c = 1; c < config.thread_pool_size; c++) { threads.emplace_back([this]() { @@ -405,11 +405,11 @@ namespace SimpleWeb { }); } - //Main thread + // Main thread if(config.thread_pool_size > 0) io_service->run(); - //Wait for the rest of the threads, if any, to finish as well + // Wait for the rest of the threads, if any, to finish as well for(auto &t : threads) t.join(); } @@ -486,16 +486,16 @@ namespace SimpleWeb { if(cancel_pair.first) return; if(!ec) { - //request->streambuf.size() is not necessarily the same as bytes_transferred, from Boost-docs: - //"After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter" - //The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the - //streambuf (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content). + // request->streambuf.size() is not necessarily the same as bytes_transferred, from Boost-docs: + // "After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter" + // The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the + // streambuf (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content). size_t num_additional_bytes = session->request->streambuf.size() - bytes_transferred; if(!session->request->parse()) return; - //If content, read that as well + // If content, read that as well auto it = session->request->header.find("Content-Length"); if(it != session->request->header.end()) { unsigned long long content_length; @@ -532,7 +532,7 @@ namespace SimpleWeb { } void find_resource(const std::shared_ptr &session) { - //Upgrade connection + // Upgrade connection if(on_upgrade) { auto it = session->request->header.find("Upgrade"); if(it != session->request->header.end()) { @@ -540,7 +540,7 @@ namespace SimpleWeb { return; } } - //Find path- and method-match, and call write_response + // Find path- and method-match, and call write_response for(auto ®ex_method : resource) { auto it = regex_method.second.find(session->request->method); if(it != regex_method.second.end()) { @@ -618,7 +618,7 @@ namespace SimpleWeb { if(cancel_pair.first) return; - //Immediately start accepting a new connection (unless io_service has been stopped) + // Immediately start accepting a new connection (unless io_service has been stopped) if(ec != asio::error::operation_aborted) this->accept(); diff --git a/tests/crypto_test.cpp b/tests/crypto_test.cpp index 2350882..028f6e4 100644 --- a/tests/crypto_test.cpp +++ b/tests/crypto_test.cpp @@ -63,7 +63,7 @@ int main() { assert(Crypto::to_hex_string(Crypto::sha512(ss)) == string_test.second); } - //Testing iterations + // Testing iterations assert(Crypto::to_hex_string(Crypto::sha1("Test", 1)) == "640ab2bae07bedc4c163f679a746f7ab7fb5d1fa"); assert(Crypto::to_hex_string(Crypto::sha1("Test", 2)) == "af31c6cbdecd88726d0a9b3798c71ef41f1624d5"); stringstream ss("Test"); diff --git a/tests/io_test.cpp b/tests/io_test.cpp index 3efff9e..01855d8 100644 --- a/tests/io_test.cpp +++ b/tests/io_test.cpp @@ -14,6 +14,7 @@ typedef SimpleWeb::Client HttpClient; int main() { { + // Test SharedMutex SimpleWeb::SharedMutex mutex; int count = 0; { @@ -109,7 +110,7 @@ int main() { }; thread server_thread([&server]() { - //Start server + // Start server server.start(); }); @@ -119,15 +120,15 @@ int main() { server_thread.join(); server_thread = thread([&server]() { - //Start server + // Start server server.start(); }); this_thread::sleep_for(chrono::seconds(1)); + // Test various request types { HttpClient client("localhost:8080"); - { stringstream output; auto r = client.request("POST", "/string", "A string"); @@ -235,6 +236,7 @@ int main() { } } + // Test asynchronous requests { HttpClient client("localhost:8080"); bool call = false; @@ -273,7 +275,7 @@ int main() { } } - /// Test concurrent synchronous request calls + // Test concurrent synchronous request calls { HttpClient client("localhost:8080"); { @@ -300,6 +302,7 @@ int main() { } } + // Test multiple requests through a persistent connection { HttpClient client("localhost:8080"); assert(client.connections.size() == 0); @@ -317,6 +320,7 @@ int main() { } } + // Test multiple requests through new several client objects for(size_t c = 0; c < 100; ++c) { { HttpClient client("localhost:8080"); diff --git a/utility.hpp b/utility.hpp index 05b17ab..cae0b48 100644 --- a/utility.hpp +++ b/utility.hpp @@ -45,7 +45,7 @@ namespace SimpleWeb { static auto hex_chars = "0123456789ABCDEF"; std::string result; - result.reserve(value.size()); // minimum size of result + result.reserve(value.size()); // Minimum size of result for(auto &chr : value) { if(chr == ' ') @@ -62,7 +62,7 @@ namespace SimpleWeb { /// Returns percent-decoded string static std::string decode(const std::string &value) { std::string result; - result.reserve(value.size() / 3 + (value.size() % 3)); // minimum size of result + result.reserve(value.size() / 3 + (value.size() % 3)); // Minimum size of result for(size_t i = 0; i < value.size(); ++i) { auto &chr = value[i]; @@ -137,7 +137,6 @@ namespace SimpleWeb { }; } -//TODO: see if there is an MSYS2 definition in an MSYS2 environment #ifdef PTHREAD_RWLOCK_INITIALIZER namespace SimpleWeb { /// Read-preferring R/W lock.