### Add Examples Subdirectory Source: https://github.com/crowcpp/crow/blob/master/CMakeLists.txt Conditionally adds the 'examples' subdirectory to the build if the CROW_BUILD_EXAMPLES option is enabled. ```cmake if(CROW_BUILD_EXAMPLES) add_subdirectory(examples) endif() ``` -------------------------------- ### Build Crow Catch-all Route Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet configures the build for an example demonstrating catch-all routes in Crow. It includes optimizations and links to the Crow library. ```cmake add_executable(example_catchall example_catchall.cpp) add_warnings_optimizations(example_catchall) target_link_libraries(example_catchall PUBLIC Crow::Crow) ``` -------------------------------- ### Install Crow using VCPKG Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/windows.md Use this command to install Crow via the VCPKG package manager on Windows. Ensure VCPKG is already installed and configured. ```bash vcpkg install crow ``` -------------------------------- ### Build Crow Middleware Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet sets up the build for an example showcasing middleware usage in Crow. It applies optimizations and links to the Crow library. ```cmake add_executable(example_middleware example_middleware.cpp) add_warnings_optimizations(example_middleware) target_link_libraries(example_middleware PUBLIC Crow::Crow) ``` -------------------------------- ### Install Python Packages for SBOM Generation Source: https://github.com/crowcpp/crow/blob/master/docs/guides/sbom.md Installs the required Python packages for SBOM generation. Ensure you are in a Python virtual environment before running this command. ```bash pip install spdx-tools reuse ntia-conformance-checker ``` -------------------------------- ### Complete Hello World App Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/your_first_application.md A complete example of a 'Hello World' application using Crow, including includes, app declaration, route definition, and running the app. ```cpp #include "crow.h" //#include "crow_all.h" int main() { crow::SimpleApp app; //define your crow application //define your endpoint at the root directory CROW_ROUTE(app, "/")([](){ return "Hello world"; }); //set the port, set the app to run on multiple threads, and run the app app.port(18080).multithreaded().run(); } ``` -------------------------------- ### Build Crow File Upload Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet sets up the build for an example that handles file uploads using Crow. It applies optimizations and links to the Crow library. ```cmake add_executable(example_file_upload example_file_upload.cpp) add_warnings_optimizations(example_file_upload) target_link_libraries(example_file_upload PUBLIC Crow::Crow) ``` -------------------------------- ### Build Crow Tests and Examples with CMake Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/macos.md Build Crow's tests and examples using CMake. This process involves creating a build directory, configuring with CMake, and then compiling. ```bash mkdir build cd build cmake .. make -j12 ``` ```bash cmake .. -DCROW_ENABLE_COMPRESSION=ON ``` ```bash cmake .. -DCROW_ENABLE_SSL=ON ``` ```bash cmake .. -DCROW_AMALGAMATE ``` -------------------------------- ### Build Crow Blueprint Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet configures the build for an example demonstrating Crow's blueprint feature for modular routing. It includes optimizations and links to the Crow library. ```cmake add_executable(example_blueprint example_blueprint.cpp) add_warnings_optimizations(example_blueprint) target_link_libraries(example_blueprint PUBLIC Crow::Crow) ``` -------------------------------- ### Build Basic Crow Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet defines a basic Crow application executable named 'basic_example'. It includes compiler optimizations and links to the Crow library. ```cmake add_executable(basic_example example.cpp) add_warnings_optimizations(basic_example) target_link_libraries(basic_example PUBLIC Crow::Crow) ``` -------------------------------- ### Build Crow Session Middleware Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet configures the build for an example demonstrating session management middleware in Crow. It includes optimizations and links to the Crow library. ```cmake add_executable(example_session middlewares/example_session.cpp) add_warnings_optimizations(example_session) target_link_libraries(example_session PUBLIC Crow::Crow) ``` -------------------------------- ### Build Crow Application with Compression Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet conditionally builds an example for compression if the 'compression' feature is enabled. It sets up the executable and links it to Crow. ```cmake # If compression is enabled, the example will be built if("compression" IN_LIST CROW_FEATURES) add_executable(example_compression example_compression.cpp) add_warnings_optimizations(example_compression) target_link_libraries(example_compression Crow::Crow) else() message(STATUS "example_compression example deactivated") endif() ``` -------------------------------- ### Build Crow Unix Socket Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet configures the build for an example that uses Unix domain sockets with Crow. It includes optimizations and links to the Crow library. ```cmake add_executable(example_unix_socket example_unix_socket.cpp) add_warnings_optimizations(example_unix_socket) target_link_libraries(example_unix_socket PUBLIC Crow::Crow) ``` -------------------------------- ### Integrate VCPKG with Visual Studio Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/windows.md Integrate VCPKG with your Visual Studio installation. This allows Visual Studio to find and use packages installed by VCPKG. ```bash .\vcpkg\vcpkg integrate install ``` -------------------------------- ### Build Crow Cookies Middleware Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet sets up the build for an example that uses cookie middleware with Crow. It applies optimizations and links to the Crow library. ```cmake add_executable(example_cookies middlewares/example_cookies.cpp) add_warnings_optimizations(example_cookies) target_link_libraries(example_cookies PUBLIC Crow::Crow) ``` -------------------------------- ### Build Crow Visual Studio Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet conditionally builds an example application for Visual Studio if the MSVC compiler is detected. It applies optimizations and links to the Crow library. ```cmake if(MSVC) add_executable(example_vs example_vs.cpp) add_warnings_optimizations(example_vs) target_link_libraries(example_vs Crow::Crow) endif() ``` -------------------------------- ### Build Crow Static File Server Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet defines how to build an example application for serving static files using Crow. It applies optimizations and links to the Crow library. ```cmake add_executable(example_static_file example_static_file.cpp) add_warnings_optimizations(example_static_file) target_link_libraries(example_static_file PUBLIC Crow::Crow) ``` -------------------------------- ### JSON Response Example Source: https://github.com/crowcpp/crow/blob/master/README.md Defines a route that returns a JSON object with multiple key-value pairs. This snippet assumes 'app' is an existing crow::SimpleApp instance. ```cpp CROW_ROUTE(app, "/json") ([]{ crow::json::wvalue x({{"message", "Hello, World!"}}); x["message2"] = "Hello, World.. Again!"; return x; }); ``` -------------------------------- ### Build Crow JSON Map Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet sets up the build for an example that uses JSON maps with Crow. It applies compiler optimizations and links to the Crow library. ```cmake add_executable(example_json_map example_json_map.cpp) add_warnings_optimizations(example_json_map) target_link_libraries(example_json_map PUBLIC Crow::Crow) ``` -------------------------------- ### Build Crow CORS Middleware Example Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet configures the build for an example demonstrating Cross-Origin Resource Sharing (CORS) middleware in Crow. It includes optimizations and links to the Crow library. ```cmake add_executable(example_cors middlewares/example_cors.cpp) add_warnings_optimizations(example_cors) target_link_libraries(example_cors PUBLIC Crow::Crow) ``` -------------------------------- ### Build Crow Application with Amalgamated Source Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet builds an example application 'example_with_all' when Crow is compiled as an amalgamated source file. It adds dependencies and includes necessary directories. ```cmake if(CROW_AMALGAMATE) add_executable(example_with_all example_with_all.cpp) add_dependencies(example_with_all crow_amalgamated) add_warnings_optimizations(example_with_all) target_link_libraries(example_with_all PUBLIC Crow::Crow) target_include_directories(example_with_all PUBLIC ${CMAKE_BINARY_DIR}) endif() ``` -------------------------------- ### Get Value from Query String Source: https://github.com/crowcpp/crow/blob/master/docs/guides/query-string.md Use get(name) to retrieve a single value associated with a key from the query string. Returns nullptr if the key is not found. ```cpp crow::request::url_params.get("key") ``` -------------------------------- ### Build Crow Application with SSL Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet conditionally builds an example for SSL if the 'ssl' feature is enabled. It configures the executable and links it to Crow. ```cmake # If SSL is enabled, the example will be built if("ssl" IN_LIST CROW_FEATURES) add_executable(example_ssl ssl/example_ssl.cpp) add_warnings_optimizations(example_ssl) target_link_libraries(example_ssl PUBLIC Crow::Crow) else() message(STATUS "example_ssl example deactivated") endif() ``` -------------------------------- ### Build Crow Chat Application Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet configures the build for a chat example application. It includes optimizations, links to Crow, and a custom command to copy the chat HTML template. ```cmake add_executable(example_chat example_chat.cpp) add_warnings_optimizations(example_chat) target_link_libraries(example_chat PUBLIC Crow::Crow) add_custom_command(OUTPUT example_chat.html COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/example_chat.html ${CMAKE_CURRENT_BINARY_DIR}/templates/example_chat.html DEPENDS ${PROJECT_SOURCE_DIR}/example_chat.html ) add_custom_target(example_chat_copy ALL DEPENDS example_chat.html) ``` -------------------------------- ### Setup Crow App with Session Middleware Source: https://github.com/crowcpp/crow/blob/master/docs/guides/included-middleware.md Configure the Crow application to use session management with a file-based store. Ensure CookieParser is listed before Session. ```cpp using Session = crow::SessionMiddleware; crow::App app{Session{ crow::FileStore{"/tmp/sessiondata"} }}; ``` -------------------------------- ### Admin Area Guard Middleware Example Source: https://github.com/crowcpp/crow/blob/master/docs/guides/middleware.md An example middleware that restricts access to admin routes based on the client's IP address. It checks the IP in `before_handle` and ends the response if unauthorized. ```cpp struct AdminAreaGuard { struct context {}; void before_handle(crow::request& req, crow::response& res, context& ctx) { if (req.remote_ip_address != ADMIN_IP) { res.code = 403; res.end(); } } void after_handle(crow::request& req, crow::response& res, context& ctx) {} }; ``` -------------------------------- ### Define Crow Library and Include Directories Source: https://github.com/crowcpp/crow/blob/master/CMakeLists.txt Defines the Crow library as an INTERFACE library and sets up include directories for both build and installation targets. ```cmake add_library(Crow INTERFACE) add_library(Crow::Crow ALIAS Crow) target_include_directories(Crow INTERFACE $ $ ) ``` -------------------------------- ### Generate crow_all.h Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/windows.md This command generates the `crow_all.h` header file from the Crow source scripts. It requires Python 3 to be installed and accessible in your PATH. ```bash python3 merge_all.py ..\include crow_all.h ``` -------------------------------- ### Define a Route Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/your_first_application.md Use the CROW_ROUTE macro to define an endpoint for your application. This example sets up a route for the root path. ```cpp CROW_ROUTE(app, "/")([](){ return "Hello world"; }); ``` -------------------------------- ### CMakeLists.txt for CrowCpp Project Source: https://github.com/crowcpp/crow/blob/master/tests/external_definition/CMakeLists.txt This CMake script configures a project to build an executable and links it with the Crow library. Ensure Crow is installed or available in your CMake environment. ```cmake project(test_external_definition) add_executable( ${PROJECT_NAME} main.cpp ) target_include_directories( ${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ) target_link_libraries( ${PROJECT_NAME} PUBLIC Crow::Crow ) ``` -------------------------------- ### URL Parameter Handling with Integer Type Source: https://github.com/crowcpp/crow/blob/master/docs/overrides/home.html This example shows how to capture integer parameters from the URL path in a Crow route. The captured integer is then converted to a string and returned as the response. This is useful for dynamic routing based on URL segments. ```cpp CROW_ROUTE(app," /hello/") ([](int count){ return crow::response(std::to_string(count)); }); ``` -------------------------------- ### Session Usage in Crow Source: https://github.com/crowcpp/crow/blob/master/docs/guides/included-middleware.md Interact with session data using get, set, remove, and keys methods. Session data is automatically persisted on first write. ```cpp auto& session = app.get_context(request); session.get("key", "not-found"); // get string by key and return "not-found" if not found session.get("int", -1); session.get("flag"); // returns default value(false) if not found session.set("key", "new value"); session.string("any-type"); // return any type as string representation session.remove("key"); session.keys(); // return list of keys ``` -------------------------------- ### Set Crow Log Level Source: https://github.com/crowcpp/crow/blob/master/docs/guides/logging.md Configure the minimum log level to display. Setting a level also displays all logs below it. For example, `Warning` will show `Warning`, `Error`, and `Critical` logs. ```cpp app.loglevel(crow::LogLevel::Warning); ``` -------------------------------- ### Compile-time Argument Type Mismatch Example Source: https://github.com/crowcpp/crow/blob/master/README.md Illustrates a compile-time error scenario where the handler function's arguments do not match the URL parameters defined in the route. This is intended to show type safety. ```cpp // Compile error with message "Handler type is mismatched with URL parameters" CROW_ROUTE(app,"/another/") ([](int a, int b){ return crow::response(500); }); ``` -------------------------------- ### Basic "Hello World" Web Service Source: https://github.com/crowcpp/crow/blob/master/docs/overrides/home.html This is the most basic Crow application. It sets up a simple web server that responds with "Hello world" to requests on the root path. Ensure you have the Crow library included. ```cpp #include "crow.h" int main() { crow::SimpleApp app; CROW_ROUTE(app, "/")([](){ return "Hello world"; }); app.port(18080).run(); } ``` -------------------------------- ### Create a Blueprint with Custom Templates Directory (No Custom Static) Source: https://github.com/crowcpp/crow/blob/master/docs/guides/blueprints.md Initialize a blueprint with a custom templates directory while using the default static directory. Pass an empty string for the static directory parameter. ```cpp crow::blueprint bp("prefix", "", "custom_templates"); ``` -------------------------------- ### Bootstrap VCPKG Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/windows.md Run the VCPKG bootstrap script to prepare VCPKG for use. This command should be executed from the root of the cloned VCPKG repository. ```bash .\vcpkg\bootstrap-vcpkg.bat ``` -------------------------------- ### Client-side Chat Logic (JavaScript) Source: https://github.com/crowcpp/crow/blob/master/examples/example_chat.html Handles sending messages via POST request and receiving logs via GET request. It also includes logic for updating the chat log display and handling Enter key presses for sending messages. ```javascript $(document).ready(function(){ $("#send").click(function(){ var msg = $("#msg").val(); console.log(msg); if (msg.length > 0) $.post("/send", msg); $("#msg").val(""); }); $("#msg").keyup(function(event){ if(event.keyCode == 13){ $("#send").click(); } }); var lastLog = 0; var updateLog; updateLog = function(data) { console.log("recv "); console.log(data); var lastLog = data.last*1; console.log("lastLog: " + lastLog); var s = ""; function htmlEncode(s) { return s.replace(/&(?!\w+(\[;\s\]|$))/g, "&") .replace(//g, ">"); } for(var x in data.msgs) { s = htmlEncode(data.msgs[x]) + "
" + s; } $("#logs").html(s+$("#logs").html()); var failFunction; failFunction = function(){ $.getJSON("/logs/"+lastLog, updateLog).fail(failFunction); }; $.getJSON("/logs/"+lastLog, updateLog).fail(failFunction); } $.getJSON("/logs", updateLog); }); ``` -------------------------------- ### Build Basic Crow Application Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet shows how to build a basic Crow application named 'helloworld'. It includes setting compiler options and linking against the Crow library. ```cmake cmake_minimum_required(VERSION 3.15) project(crow_examples) include(${CMAKE_SOURCE_DIR}/cmake/compiler_options.cmake) add_executable(helloworld helloworld.cpp) add_warnings_optimizations(helloworld) target_link_libraries(helloworld PUBLIC Crow::Crow) ``` -------------------------------- ### Create a Blueprint with Custom Templates Directory Source: https://github.com/crowcpp/crow/blob/master/docs/guides/blueprints.md Initialize a blueprint with custom static and template directories. Routes within this blueprint will use the specified template directory for loading templates. ```cpp crow::blueprint bp("prefix", "custom_static", "custom_templates"); ``` -------------------------------- ### Create a Blueprint with a Prefix Source: https://github.com/crowcpp/crow/blob/master/docs/guides/blueprints.md Initialize a blueprint with a string prefix. This prefix will be prepended to all routes defined within this blueprint. ```cpp crow::blueprint bp("prefix"); ``` -------------------------------- ### Basic Hello World Route Source: https://github.com/crowcpp/crow/blob/master/README.md Sets up a simple Crow application with a single route that returns 'Hello world'. Ensure you define CROW_MAIN in one source file if using Crow v0.3. ```cpp #include "crow.h" int main() { crow::SimpleApp app; CROW_ROUTE(app, "/")([](){ return "Hello world"; }); app.port(18080).multithreaded().run(); } ``` -------------------------------- ### Create a Blueprint with Custom Static Directory Source: https://github.com/crowcpp/crow/blob/master/docs/guides/blueprints.md Initialize a blueprint specifying a custom static directory. This directory will be used for serving static files directly. ```cpp crow::blueprint bp("prefix", "custom_static"); ``` -------------------------------- ### Configure SSL with Fullchain Certificate and Key Files Source: https://github.com/crowcpp/crow/blob/master/docs/guides/ssl.md Use this method when dealing with fullchain certificate files (e.g., from Let's Encrypt). This ensures the CA part is correctly processed by Crow, preventing certificate verification errors. ```cpp app.ssl_chainfile("/path/to/fullchain.cer", "/path/to/keyfile.key") ``` -------------------------------- ### Client-side Certificate Verification Error Example Source: https://github.com/crowcpp/crow/blob/master/docs/guides/ssl.md This error can occur if a fullchain certificate is not handled correctly by Crow using `ssl_chainfile`. ```bash ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1007) ``` -------------------------------- ### Initialize wvalue as a list Source: https://github.com/crowcpp/crow/blob/master/docs/guides/json.md Create a wvalue list using a predefined list of values. Lists can contain elements of any type supported by wvalue. ```cpp wvalue x = json::wvalue::list({1, 2, 3}); ``` -------------------------------- ### Configure SSL with Custom Asio Context Source: https://github.com/crowcpp/crow/blob/master/docs/guides/ssl.md Allows setting a custom SSL context using `asio::ssl::context` and applying it to the Crow application via the `ssl` method. ```cpp app.ssl(ctx) ``` -------------------------------- ### Build Crow with SBOM Generation Enabled Source: https://github.com/crowcpp/crow/blob/master/docs/guides/sbom.md Configures and builds the Crow project with SBOM generation enabled. It's crucial to specify the Python 3 executable from your virtual environment using -DPython3_EXECUTABLE to ensure the SBOM verification step succeeds. ```bash cmake .. -DCROW_GENERATE_SBOM=ON -DPython3_EXECUTABLE=$(which python3) ``` ```bash cmake --build . ``` ```bash cmake --install . --prefix /tmp/crow-install ``` -------------------------------- ### Define Project and Include Directories Source: https://github.com/crowcpp/crow/blob/master/tests/template/CMakeLists.txt Sets the minimum CMake version, project name, and include directories for the project. ```cmake cmake_minimum_required(VERSION 3.15) project(template_test) set(PROJECT_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include ) ``` -------------------------------- ### Decode Basic Auth Credentials in Crow Source: https://github.com/crowcpp/crow/blob/master/docs/guides/auth.md Extracts and decodes the Base64 encoded username and password from the 'Authorization' header for Basic Authentication. Assumes the header starts with 'Basic '. ```cpp std::string mycreds = myauth.substr(6); std::string d_mycreds = crow::utility::base64decode(mycreds, mycreds.size()); ``` -------------------------------- ### Initialize wvalue as an object Source: https://github.com/crowcpp/crow/blob/master/docs/guides/json.md Create a wvalue object using an initializer list, providing key-value pairs. This is a convenient way to construct JSON objects. ```cpp wvalue x = {{"a", 1}, {"b", 2}}; ``` -------------------------------- ### Remove and Get List of Values from Query String Source: https://github.com/crowcpp/crow/blob/master/docs/guides/query-string.md Use pop_list(name) to retrieve and remove all values associated with a key from the query string. The use_brackets parameter is also available. ```cpp crow::request::url_params.pop_list("key") ``` -------------------------------- ### Configure ASIO Dependency and Version Source: https://github.com/crowcpp/crow/blob/master/CMakeLists.txt Finds the ASIO library if Boost is not used, links it to Crow, and attempts to determine the ASIO version from its header file. Includes SBOM generation. ```cmake if(ASIO_FOUND) find_file(ASIO_VERSION_HPP "asio/version.hpp" PATHS ${ASIO_INCLUDE_DIR}) if(ASIO_VERSION_HPP) file(READ ${ASIO_VERSION_HPP} ASIO_VERSION_CONTENT) string(REGEX MATCH "#define ASIO_VERSION ([0-9]+)" _ ${ASIO_VERSION_CONTENT}) if(CMAKE_MATCH_1) math(EXPR ASIO_VERSION_MAJOR "${CMAKE_MATCH_1} / 100000") math(EXPR ASIO_VERSION_MINOR "(${CMAKE_MATCH_1} / 1000) % 100") math(EXPR ASIO_VERSION_PATCH "${CMAKE_MATCH_1} % 1000") set(asio_VERSION "${ASIO_VERSION_MAJOR}.${ASIO_VERSION_MINOR}.${ASIO_VERSION_PATCH}") endif() endif() # Fallback if(NOT asio_VERSION) set(asio_VERSION "unknown") endif() if(CROW_GENERATE_SBOM) sbom_add( PACKAGE asio DOWNLOAD_LOCATION https://github.com/chriskohlhoff/asio LICENSE "BSL-1.0" SUPPLIER "Organization: Boost Community" VERSION "${asio_VERSION}" ) endif() endif() ``` -------------------------------- ### Configure and Run Crow App Source: https://github.com/crowcpp/crow/blob/master/docs/guides/app.md Chains configuration methods for binding address, port, SSL, and multithreading, followed by running the app. Use this for a concise, single-line configuration. ```cpp app.bindaddr("192.168.1.2").port(443).ssl_file("certfile.crt","keyfile.key").multithreaded().run(); ``` ```cpp app.bindaddr("192.168.1.2") .port(443) .ssl_file("certfile.crt","keyfile.key") .multithreaded() .run(); ``` -------------------------------- ### Extract Access Token for Bearer Authentication in Crow Source: https://github.com/crowcpp/crow/blob/master/docs/guides/auth.md Extracts the access token from the 'Authorization' header when using Bearer authentication. It assumes the header starts with 'Bearer ' and removes this prefix. ```cpp std::string myauth = req.get_header_value("Authorization"); std::string mycreds = myauth.substr(7); // The length can change based on the keyword used /*Verify validity of the token here*/ return true; //or false if the token is invalid ``` -------------------------------- ### Configure SSL with Certificate and Key Files Source: https://github.com/crowcpp/crow/blob/master/docs/guides/ssl.md Use this method to configure SSL for your Crow application by providing separate certificate and key files. This can be chained with other app methods. ```cpp app.ssl_file("/path/to/cert.crt", "/path/to/keyfile.key") ``` -------------------------------- ### Create and Render Mustache Context Source: https://github.com/crowcpp/crow/blob/master/docs/guides/templating.md Create a Mustache context, assign key-value pairs, and render a template with this context. The context is a crow::json::wvalue. ```cpp crow::mustache::context ctx; ctx["key"] = value; return page.render(ctx); ``` -------------------------------- ### Nginx Root Location Proxy Configuration Source: https://github.com/crowcpp/crow/blob/master/docs/guides/proxies.md Configure Nginx to proxy requests to your Crow application. Ensure any existing `location /` block is removed or commented out. This setup proxies to the root directory. ```nginx location / { proxy_pass http://localhost:40080/; proxy_http_version 1.1; } ``` -------------------------------- ### Create a Basic HTML Page Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/a_simple_webpage.md This is the HTML content for a simple webpage. Place this file in the 'templates' directory. ```html

Hello World!

``` -------------------------------- ### Test Crow Application with ASIO Client Source: https://github.com/crowcpp/crow/blob/master/docs/guides/testing.md This method simulates a real client request using ASIO for more realistic testing, including post-handle operations. It involves setting up an ASIO client to connect to a running Crow application, send an HTTP request, and receive the response. Ensure `app.stop()` is called to prevent test hangs. ```cpp static char buf[2048]; SimpleApp app; CROW_ROUTE(app, "/")([] { return "A"; }); auto _ = async(launch::async,[&] { app1.bindaddr("127.0.0.1").port(45451).run(); }); app.wait_for_server_start(); std::string sendmsg = "GET /\r\nContent-Length:3\r\nX-HeaderTest: 123\r\n\r\nA=B\r\n"; asio::io_service is; { asio::ip::tcp::socket c(is); c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string("127.0.0.1"), 45451)); c.send(asio::buffer(sendmsg)); size_t recved = c.receive(asio::buffer(buf, 2048)); CHECK('A' == buf[recved - 1]); //This is specific to catch2 testing library, but it should give a general idea of how to read the response. } app.stop(); //THIS MUST RUN } ``` -------------------------------- ### Apache2 Proxy Configuration Source: https://github.com/crowcpp/crow/blob/master/docs/guides/proxies.md Configure Apache2 to proxy requests to your Crow application. Replace `localhost` and `40080` with your Crow app's address and port. This setup is for proxying to the root directory. ```apache ProxyPass / http://localhost:40080 ProxyPassReverse / http://localhost:40080 ``` -------------------------------- ### Using crow::status for Response Codes Source: https://github.com/crowcpp/crow/blob/master/docs/guides/routes.md Replace integer status codes with the crow::status enum for better readability and maintainability. For example, use crow::status::OK instead of 200. ```cpp crow::response(crow::status::OK) ``` -------------------------------- ### Set Permissions for Systemd Service File Source: https://github.com/crowcpp/crow/blob/master/docs/guides/syste.md After creating the service unit file, set the correct permissions to ensure Systemd can read and execute it. A 'sudo' command might be necessary. ```sh chmod 640 /etc/systemd/system/crowthing.service ``` -------------------------------- ### Define Fuzzer Target with CMake Source: https://github.com/crowcpp/crow/blob/master/tests/fuzz/CMakeLists.txt Defines a CMake function to create an executable for a fuzzer. It links against the Crow library and the fuzzing engine, sets C++17 standard, and installs the target if the OUT environment variable is set. ```cmake cmake_minimum_required(VERSION 3.14) function(define_fuzzer executable_name) add_executable(${executable_name} ${executable_name}.cpp) target_link_libraries(${executable_name} PRIVATE Crow $ENV{LIB_FUZZING_ENGINE}) target_compile_features(${executable_name} PRIVATE cxx_std_17) if (DEFINED ENV{OUT}) install(TARGETS ${executable_name} DESTINATION $ENV{OUT}) else () message(WARNING "Cannot install if $OUT is not defined!") endif () endfunction() ``` -------------------------------- ### Serve a Static HTML Page with Crow Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/a_simple_webpage.md This C++ code sets up a Crow application to serve a static HTML file from the 'templates' directory when the root URL is accessed. ```cpp #include "crow.h" //#include "crow_all.h" int main() { crow::SimpleApp app; //define your crow application //define your endpoint at the root directory CROW_ROUTE(app, "/")([](){ auto page = crow::mustache::load_text("fancypage.html"); return page; }); app.port(18080).multithreaded().run(); } ``` -------------------------------- ### Remove and Get Dictionary from Query String Source: https://github.com/crowcpp/crow/blob/master/docs/guides/query-string.md Use pop_dict(name) to retrieve and remove values from a query string formatted with bracket notation. Be cautious when mixing with pop_list on the same key, as list items can overwrite dictionary entries. ```cpp crow::request::url_params.pop_dict("key") ``` -------------------------------- ### Build Crow with SBOM and Other Features Enabled Source: https://github.com/crowcpp/crow/blob/master/docs/guides/sbom.md Combines SBOM generation with other build options like SSL and compression. This demonstrates how to enable multiple features simultaneously during the CMake configuration step. ```bash cmake .. -DCROW_GENERATE_SBOM=ON -DCROW_ENABLE_SSL=ON -DCROW_ENABLE_COMPRESSION=ON ``` -------------------------------- ### Remove and Get Value from Query String Source: https://github.com/crowcpp/crow/blob/master/docs/guides/query-string.md Use pop(name) to retrieve and remove a value associated with a key from the query string. Note that crow::request::url_params is const, so a copy must be made for pop to work. ```cpp crow::request::url_params.pop("key") ``` -------------------------------- ### Get List of Values from Query String Source: https://github.com/crowcpp/crow/blob/master/docs/guides/query-string.md Use get_list(name) to retrieve all values associated with a key that may appear multiple times in the query string, formatted as key[]=value. Returns an std::vector. ```cpp crow::request::url_params.get_list("key") ``` -------------------------------- ### Define Static File Directory and Endpoint Macros Source: https://github.com/crowcpp/crow/blob/master/docs/guides/static.md Change the default 'static' directory and '/static/' endpoint for implicit static file serving by defining these macros. ```cpp #define CROW_STATIC_DIRECTORY "alternative_directory/" #define CROW_STATIC_ENDPOINT "/alternative_endpoint/" ``` -------------------------------- ### Get Dictionary from Query String Source: https://github.com/crowcpp/crow/blob/master/docs/guides/query-string.md Use get_dict(name) to retrieve values from a query string formatted with bracket notation, like key[sub_key]=value. Returns an std::unordered_map where keys are the sub-keys. ```cpp crow::request::url_params.get_dict("key") ``` -------------------------------- ### Run Crow App Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/your_first_application.md Configure and run the Crow application. The port and multithreading options are optional. ```cpp app.port(18080).multithreaded().run(); ``` -------------------------------- ### Build Crow WebSocket Application Source: https://github.com/crowcpp/crow/blob/master/examples/CMakeLists.txt This CMakeLists.txt snippet sets up a Crow application for WebSocket communication. It defines the executable, applies optimizations, links to Crow, and includes a custom command to copy WebSocket template files. ```cmake add_executable(example_websocket websocket/example_ws.cpp) add_warnings_optimizations(example_websocket) target_link_libraries(example_websocket PUBLIC Crow::Crow) add_custom_command(OUTPUT ws.html COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/websocket/templates/ws.html ${CMAKE_CURRENT_BINARY_DIR}/templates/ws.html DEPENDS ${PROJECT_SOURCE_DIR}/websocket/templates/ws.html ) add_custom_target(example_ws_copy ALL DEPENDS ws.html) ``` -------------------------------- ### Configure ZLIB Compression Dependency Source: https://github.com/crowcpp/crow/blob/master/CMakeLists.txt Finds and configures the ZLIB library for compression support, linking it to Crow and enabling the compression feature. Includes SBOM generation. ```cmake if(CROW_ENABLE_COMPRESSION) find_package(ZLIB REQUIRED) target_link_libraries(Crow INTERFACE ZLIB::ZLIB) target_compile_definitions(Crow INTERFACE CROW_ENABLE_COMPRESSION) if(CROW_GENERATE_SBOM) sbom_add( PACKAGE zlib DOWNLOAD_LOCATION https://github.com/madler/zlib LICENSE "Zlib" SUPPLIER "Person: Jean-loup Gailly and Mark Adler" VERSION "${ZLIB_VERSION}" ) endif() endif() ``` -------------------------------- ### Configure OpenSSL Dependency for SSL Support Source: https://github.com/crowcpp/crow/blob/master/CMakeLists.txt Finds and configures the OpenSSL library for SSL support, linking it to Crow and enabling the SSL feature. Includes SBOM generation. ```cmake if(CROW_ENABLE_SSL) find_package(OpenSSL REQUIRED) target_link_libraries(Crow INTERFACE OpenSSL::SSL) target_compile_definitions(Crow INTERFACE CROW_ENABLE_SSL) if(CROW_GENERATE_SBOM) sbom_add( PACKAGE openssl DOWNLOAD_LOCATION https://github.com/openssl/openssl LICENSE "Apache-2.0" SUPPLIER "Organization: OpenSSL Software Foundation" VERSION "${OPENSSL_VERSION}" ) endif() endif() ``` -------------------------------- ### Systemd Service Unit File for Crow Application Source: https://github.com/crowcpp/crow/blob/master/docs/guides/syste.md This file configures Systemd to manage your Crow application. Ensure 'ExecStart' points to the absolute path of your executable. The service will restart automatically if it fails. ```sh [Unit] Description=My revolutionary Crow application Wants=network.target After=syslog.target network-online.target [Service] Type=simple ExecStart=/absolute/path/to/your/executable Restart=on-failure RestartSec=10 KillMode=process [Install] WantedBy=multi-user.target ``` -------------------------------- ### Define Executable and Link Libraries Source: https://github.com/crowcpp/crow/blob/master/tests/template/CMakeLists.txt Defines the source files for the executable and links it against the Crow library. Also enables warnings and optimizations. ```cmake set(TEST_SRCS mustachetest.cpp ) add_executable(mustachetest ${TEST_SRCS}) target_link_libraries(mustachetest Crow::Crow) add_warnings_optimizations(mustachetest) ``` -------------------------------- ### Middleware before_handle Signature with Context Access Source: https://github.com/crowcpp/crow/blob/master/docs/guides/middleware.md Demonstrates the signature for `before_handle` that allows access to the current middleware's context only. This is used when no other middleware contexts are needed. ```cpp void before_handle(request& req, response& res, context& ctx) ``` -------------------------------- ### Defining Routes with CROW_ROUTE Source: https://github.com/crowcpp/crow/blob/master/docs/guides/routes.md Demonstrates the basic usage of the CROW_ROUTE macro for defining application routes and associating them with handlers. ```APIDOC ## CROW_ROUTE Macro ### Description The `CROW_ROUTE` macro is used to define a route in the CrowCpp application, mapping a URL path to a specific handler function. ### Usage `CROW_ROUTE(app, url)` Alternatively, for runtime URL evaluation (not recommended): `app.route_dynamic(url)` Or using C++11 features: `app.route(url)` ### Parameters - **app**: The Crow application instance. - **url**: The relative path for the route. ### Example ```cpp CROW_ROUTE(app, "/hello") ([]() { return "Hello World"; }); ``` ``` -------------------------------- ### Specifying HTTP Methods Source: https://github.com/crowcpp/crow/blob/master/docs/guides/routes.md Details how to specify which HTTP methods a route should respond to. ```APIDOC ## Specifying HTTP Methods ### Description By default, routes respond to `GET` requests. You can specify multiple HTTP methods for a route using the `.methods()` modifier. ### Usage `CROW_ROUTE(app, url).methods(method1, method2, ...)` Or using string literals for methods: `CROW_ROUTE(app, url).methods("METHOD1"_method, "METHOD2"_method)` ### Supported Methods Crow supports a wide range of HTTP methods including `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTIONS`, `HEAD`, etc. ### Notes - `OPTIONS` method is handled automatically by Crow. - `HEAD` method is handled automatically unless explicitly defined in a route. - Adding `OPTIONS` to a route's methods has no effect. ### Example ```cpp CROW_ROUTE(app, "/resource").methods(crow::HTTPMethod::GET, crow::HTTPMethod::PATCH) ([]() { // Handler for GET and PATCH requests return "Resource accessed"; }); ``` ``` -------------------------------- ### Define a Catchall Route for a Blueprint Source: https://github.com/crowcpp/crow/blob/master/docs/guides/blueprints.md Define a custom catchall route for a blueprint. This route will handle requests that match the blueprint's prefix but do not have a specific route defined. ```cpp CROW_BP_CATCHALL_ROUTE(blueprint) ``` -------------------------------- ### Enable Crow HTTP Compression Source: https://github.com/crowcpp/crow/blob/master/docs/guides/compression.md Define CROW_ENABLE_COMPRESSION during compilation or in CMakeLists.txt to enable HTTP compression. Ensure ZLIB is linked. ```bash g++ main.cpp -DCROW_ENABLE_COMPRESSION ``` ```cmake set(CROW_ENABLE_COMPRESSION ON) ``` -------------------------------- ### Compile Project with g++ Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/linux.md Use this command to compile your main C++ file with Crow. You can add flags for debugging, compression, or SSL support. ```bash g++ main.cpp -lpthread ``` -------------------------------- ### Use Compression Algorithm in Crow Source: https://github.com/crowcpp/crow/blob/master/docs/guides/compression.md Call use_compression on your Crow app instance, specifying either crow::compression::algorithm::DEFLATE or crow::compression::algorithm::GZIP. This enables compression for HTTP responses. ```cpp #!cpp use_compression(crow::compression::algorithm) ``` ```cpp crow::compression::algorithm::DEFLATE ``` ```cpp crow::compression::algorithm::GZIP ``` -------------------------------- ### Serve Dynamic HTML with Variables using Crow Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/a_simple_webpage.md This C++ code configures a Crow route to accept a string from the URL, load an HTML template, and render it with a dynamic 'person' variable. ```cpp #include "crow.h" //#include "crow_all.h" int main() { crow::SimpleApp app; //define your endpoint at the root directory CROW_ROUTE(app, "/")([](std::string name){ // (1) auto page = crow::mustache::load("fancypage.html"); // (2) crow::mustache::context ctx ({{"person", name}}); // (3) return page.render(ctx); //(4) }); app.port(18080).multithreaded().run(); } ``` -------------------------------- ### Middleware before_handle Signature with All Context Access Source: https://github.com/crowcpp/crow/blob/master/docs/guides/middleware.md Shows the `before_handle` signature that provides access to all middleware contexts. This is useful for inter-middleware communication or data retrieval. ```cpp template void before_handle(request& req, response& res, context& ctx, AllContext& all_ctx) { auto other_ctx = all_ctx.template get(); } ``` -------------------------------- ### Configure Boost Dependency Source: https://github.com/crowcpp/crow/blob/master/CMakeLists.txt Finds and configures the Boost library, including specific components like date_time and system, and links them to the Crow library. Handles different Boost versions and SBOM generation. ```cmake if(CROW_USE_BOOST) if(POLICY CMP0167) # Use Boost CMake module from Boost instead of the one from CMake cmake_policy(SET CMP0167 NEW) endif() find_package(Boost 1.64 COMPONENTS date_time REQUIRED) if(Boost_VERSION VERSION_LESS 1.89) find_package(Boost 1.64 COMPONENTS system REQUIRED) else() if(NOT TARGET Boost::system) add_library(Boost::system ALIAS Boost::headers) endif() endif() target_link_libraries(Crow INTERFACE Boost::boost Boost::system Boost::date_time ) target_compile_definitions(Crow INTERFACE CROW_USE_BOOST) if(CROW_GENERATE_SBOM) sbom_add( PACKAGE boost DOWNLOAD_LOCATION https://www.boost.org/ LICENSE "BSL-1.0" SUPPLIER "Organization: Boost Community" VERSION "${Boost_VERSION}" ) endif() else() find_package(asio REQUIRED) target_link_libraries(Crow INTERFACE asio::asio ) target_compile_definitions(Crow INTERFACE ASIO_NO_DEPRECATED) endif() ``` -------------------------------- ### Enable Apache2 Proxy Modules Source: https://github.com/crowcpp/crow/blob/master/docs/guides/proxies.md Use these commands to enable essential Apache2 modules for reverse proxy functionality. Ensure these modules are enabled before configuring your virtual host. ```sh a2enmod proxy a2enmod proxy_http a2enmod proxy_html a2enmod proxy_wstunnel ``` -------------------------------- ### Enabling Local Middleware for a Blueprint Source: https://github.com/crowcpp/crow/blob/master/docs/guides/middleware.md Attach local middleware to an entire blueprint using `bp.CROW_MIDDLEWARES()`. All routes within that blueprint will then be subject to the specified middleware. ```cpp Blueprint bp("with_middleware"); bp.CROW_MIDDLEWARES(app, FistLocalMiddleware, SecondLocalMiddleware); ``` -------------------------------- ### Route Path Parameters Source: https://github.com/crowcpp/crow/blob/master/docs/guides/routes.md Explains how to define dynamic parameters within route paths and access them in handlers. ```APIDOC ## Route Path Parameters ### Description Route paths can include parameters that capture parts of the URL. These parameters can be of various types and are passed to the handler function. ### Parameter Types - ``: Integer - ``: Unsigned Integer - ``: Double-precision floating-point number - ``: String - ``: Captures the rest of the path ### Example ```cpp CROW_ROUTE(app, "/add//") ([](int a, int b) { return std::to_string(a + b); }); ``` Calling `http://example.com/add/1/2` will result in `3`. ``` -------------------------------- ### Explicitly Serve Static Files with Crow Source: https://github.com/crowcpp/crow/blob/master/docs/guides/static.md Use the CROW_STATIC_FILE macro or the app.static_file() function to explicitly map URL endpoints to specific static files. The file path is relative to the working directory. ```cpp auto app = crow::SimpleApp(); // or crow::App() // by Macro CROW_STATIC_FILE(app, "/" , "home.html"); CROW_STATIC_FILE(app, "/home.html" , "home.html"); // by Function app.static_file("/favicon.ico", "images/home.png"); app.static_file("/style.css", "style.css"); ``` -------------------------------- ### Compile Project with g++ and Options Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/linux.md Compile your C++ project with Crow, enabling optional features like debug mode, HTTP compression (linking with zlib), or HTTPS support (linking with OpenSSL). ```bash g++ main.cpp -lpthread -DCROW_ENABLE_DEBUG -DCROW_ENABLE_COMPRESSION -lz -DCROW_ENABLE_SSL -lssl ``` -------------------------------- ### Configure SSL with PEM File Source: https://github.com/crowcpp/crow/blob/master/docs/guides/ssl.md Use this method to configure SSL for your Crow application using a single PEM file. This can be chained with other app methods. ```cpp app.ssl_file("/path/to/pem_file.pem") ``` -------------------------------- ### Load Mustache Template from File Source: https://github.com/crowcpp/crow/blob/master/docs/guides/templating.md Load a Mustache template from a file located relative to the configured templates directory. The path is sanitized by default. ```cpp auto page = crow::mustache::load("path/to/template.html"); ``` -------------------------------- ### Copy Test Files and Create Custom Command Source: https://github.com/crowcpp/crow/blob/master/tests/template/CMakeLists.txt Copies JSON files and a Python test script to the build directory. This is done to ensure the test script is available in the build environment. ```cmake if(NOT MSVC) # there is a bug in the python script, it does not find the path file(COPY DIRECTORY . DESTINATION ${CMAKE_CURRENT_BINARY_DIR} FILES_MATCHING PATTERN "*.json") add_custom_command(OUTPUT test.py COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/test.py ${CMAKE_CURRENT_BINARY_DIR}/test.py DEPENDS ${PROJECT_SOURCE_DIR}/test.py ) add_custom_target(template_test_copy ALL DEPENDS test.py) add_test( NAME template_test COMMAND python3 ${CMAKE_CURRENT_BINARY_DIR}/test.py WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) endif() ``` -------------------------------- ### Defining a Catchall Route Source: https://github.com/crowcpp/crow/blob/master/docs/guides/routes.md Implement a catchall route using the CROW_CATCHALL_ROUTE macro to handle requests that do not match any defined routes. This macro accepts optional request and response parameters. ```cpp CROW_CATCHALL_ROUTE(app) ``` -------------------------------- ### Handling JSON POST Requests Source: https://github.com/crowcpp/crow/blob/master/README.md Defines a POST route that accepts JSON data in the request body. It parses the JSON, performs a calculation, and returns the result. This snippet assumes 'app' is an existing crow::SimpleApp instance. ```cpp CROW_ROUTE(app, "/add_json") .methods("POST"_method) ([](const crow::request& req){ auto x = crow::json::load(req.body); if (!x) return crow::response(crow::status::BAD_REQUEST); // same as crow::response(400) int sum = x["a"].i()+x["b"].i(); std::ostringstream os; os << sum; return crow::response{os.str()}; }); ``` -------------------------------- ### Generate Single Header File with Python Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/macos.md Use this script to generate a single header file for Crow from its source files. This is recommended for smaller projects. ```bash python3 merge_all.py ../include crow_all.h ``` -------------------------------- ### Request Handling Source: https://github.com/crowcpp/crow/blob/master/docs/guides/routes.md Explains how to access request details and URL parameters within a handler. ```APIDOC ## Request Handling ### Description Handlers can access information about the incoming request, including request parameters and body content. ### Accessing Request Object Include `const crow::request& req` as a parameter in your handler lambda. ### Accessing URL Parameters Use `req.url_params.get("param_name")` to retrieve URL parameters. Returns `nullptr` if the parameter does not exist. ### Accessing Body Parameters For `application/x-www-form-urlencoded` requests, use `req.get_body_params()`. ### Example ```cpp CROW_ROUTE(app, "/user/") ([](const crow::request& req, std::string user_id) { std::string username = req.url_params.get("username"); // Example of accessing a query parameter if it were present // Process user_id and potentially other request details return "User ID: " + user_id; }); ``` For more information on `crow::request`, refer to the [CrowCpp documentation](../reference/structcrow_1_1request.html). ``` -------------------------------- ### Clone VCPKG repository Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/setup/windows.md Clone the official VCPKG repository to your local machine. This is necessary for integrating VCPKG with your development environment. ```bash git clone https://github.com/microsoft/vcpkg.git ``` -------------------------------- ### Declare Crow App Source: https://github.com/crowcpp/crow/blob/master/docs/getting_started/your_first_application.md Declare a crow::SimpleApp instance within your main function to manage Crow components. ```cpp int main() { crow::SimpleApp app; } ```