### Multiple Path Mapping Example Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-04-2-Controller-HttpController Demonstrates mapping multiple HTTP methods (GET, POST, DELETE) to different handler functions for the same base path. ```cpp METHOD_LIST_BEGIN METHOD_ADD(Book::getInfo,"/{1}?detail={2}",Get); METHOD_ADD(Book::newBook,"/{1}",Post); METHOD_ADD(Book::deleteOne,"/{1}",Delete); METHOD_LIST_END ``` -------------------------------- ### Basic Drogon Application Setup Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-FAQ-1-Understanding-drogon-threading-model Sets up a simple HTTP handler, listener, and specifies the number of worker threads for a Drogon application. This is a typical starting point for a Drogon app. ```cpp #include using namespace drogon; int main() { app().registerHandler("/", [](const HttpRequest& req , std::function &&callback) { auto resp = HttpResponse::newHttpResponse(); resp->setBody("Hello wrold"); callback(resp); }); app().addListener("0.0.0.0", 80800); app().setNumThreads(3); app().run(); } ``` -------------------------------- ### Drogon Application Setup with Configuration File Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/index.html Demonstrates how to simplify Drogon application setup by loading configurations from a JSON file. ```c++ #include using namespace drogon; int main() { app().loadConfigFile("./config.json"); app().run(); } ``` -------------------------------- ### User RESTful API Controller Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/index.html This example shows a User controller that handles GET and POST requests for user information. It demonstrates path parameters and asynchronous handling. ```APIDOC ## GET /api/v1/User/{1} ### Description Retrieves information for a specific user based on their ID. ### Method GET ### Endpoint /api/v1/User/{userId} ### Parameters #### Path Parameters - **userId** (int) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **(structure depends on implementation)** ## GET /api/v1/User/{1}/detailinfo ### Description Retrieves detailed information for a specific user. ### Method GET ### Endpoint /api/v1/User/{userId}/detailinfo ### Parameters #### Path Parameters - **userId** (int) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **(structure depends on implementation)** ## POST /api/v1/User/{1} ### Description Creates a new user with the provided username. ### Method POST ### Endpoint /api/v1/User/{userName} ### Parameters #### Path Parameters - **userName** (string) - Required - The username for the new user. ### Response #### Success Response (200) - **(structure depends on implementation)** ``` -------------------------------- ### HttpController for RESTful API Source: https://github.com/drogonframework/drogon/blob/master/README.md Demonstrates creating a RESTful API endpoint using HttpController. This example defines handlers for getting user information and details, and creating a new user. ```APIDOC ## HttpController for RESTful API ### Description Defines a RESTful API controller using the HttpController class. ### Header File ```cpp #pragma once #include using namespace drogon; namespace api { namespace v1 { class User : public drogon::HttpController { public: METHOD_LIST_BEGIN //use METHOD_ADD to add your custom processing function here; METHOD_ADD(User::getInfo, "/{id}", Get); //path is /api/v1/User/{arg1} METHOD_ADD(User::getDetailInfo, "/{id}/detailinfo", Get); //path is /api/v1/User/{arg1}/detailinfo METHOD_ADD(User::newUser, "/{name}", Post); //path is /api/v1/User/{arg1} METHOD_LIST_END //your declaration of processing function maybe like this: void getInfo(const HttpRequestPtr &req, std::function &&callback, int userId) const; void getDetailInfo(const HttpRequestPtr &req, std::function &&callback, int userId) const; void newUser(const HttpRequestPtr &req, std::function &&callback, const std::string &userName) const; }; } } ``` ``` -------------------------------- ### Install jsoncpp on Arch Linux Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the JSON C++ library on Arch Linux. ```shell sudo pacman -S jsoncpp ``` -------------------------------- ### Windows Source Installation - Build and Install Source: https://github.com/drogonframework/drogon/wiki/CHN/CHN-02-安装 Compile and install Drogon on Windows using CMake after dependency installation. Ensure CMake toolchain file and build type consistency. ```shell cmake .. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_TOOLCHAIN_FILE="conan_toolchain.cmake" -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_INSTALL_PREFIX="D:" cmake --build . --parallel --target install ``` -------------------------------- ### Install Redis Development Libraries Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the hiredis library for Redis integration. Select the command appropriate for your system. ```bash sudo apt-get install libhiredis-dev ``` ```bash sudo pacman -S redis ``` ```bash yum install hiredis-devel ``` ```bash brew install hiredis ``` ```bash hiredis/1.0.0 ``` -------------------------------- ### Install zlib Development Files on Ubuntu Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the zlib compression library development files on Ubuntu. ```shell sudo apt install zlib1g-dev ``` -------------------------------- ### Simple Controller Example Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/a-directory/page.html Demonstrates a basic controller that returns a 'Hello, world!' string for a given URL. ```APIDOC ## GET /test ### Description Handles requests to the /test endpoint and returns a simple HTML response. ### Method GET ### Endpoint /test ### Request Example (No request body for this GET request) ### Response #### Success Response (200) - **body** (string) - HTML content, e.g., "

Hello, world!

" ``` -------------------------------- ### Install zlib on Arch Linux Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the zlib compression library on Arch Linux. ```shell sudo pacman -S zlib ``` -------------------------------- ### Install libuuid Development Files on Ubuntu Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the library for generating UUIDs on Ubuntu. ```shell sudo apt install uuid-dev ``` -------------------------------- ### Install Sqlite3 Development Libraries Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the Sqlite3 development libraries for database integration. Choose the command based on your operating system. ```bash sudo apt-get install libsqlite3-dev ``` ```bash sudo pacman -S sqlite3 ``` ```bash yum install sqlite-devel ``` ```bash brew install sqlite3 ``` ```bash sqlite3/3.36.0 ``` -------------------------------- ### Install Git, GCC, and CMake on Ubuntu Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs essential build tools for Drogon on Ubuntu 24.04. ```shell sudo apt install git gcc g++ cmake ``` -------------------------------- ### HttpSimpleController Example Source: https://github.com/drogonframework/drogon/blob/master/README.md Demonstrates creating a simple controller by inheriting from HttpSimpleController. This example defines a controller for the '/test' path that returns a plain text response. ```APIDOC ## HttpSimpleController ### Description Defines a simple HTTP controller for handling requests. ### Header File (`TestCtrl.h`) ```cpp #pragma once #include using namespace drogon; class TestCtrl:public drogon::HttpSimpleController { public: void asyncHandleHttpRequest(const HttpRequestPtr& req, std::function &&callback) override; PATH_LIST_BEGIN PATH_ADD("/test",Get); PATH_LIST_END }; ``` ### Source File (`TestCtrl.cc`) ```cpp #include "TestCtrl.h" void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req, std::function &&callback) { //write your application logic here auto resp = HttpResponse::newHttpResponse(); resp->setBody("

Hello, world!

"); resp->setExpiredTime(0); callback(resp); } ``` ``` -------------------------------- ### Install Git on CentOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the Git version control system on CentOS 7.5. ```shell yum install git ``` -------------------------------- ### Install jsoncpp from Source on CentOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Builds and installs the jsoncpp library from source on CentOS 7.5. ```shell git clone https://github.com/open-source-parsers/jsoncpp cd jsoncpp/ mkdir build cd build cmake .. make && make install ``` -------------------------------- ### Install PostgreSQL Development Libraries Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the PostgreSQL native C library (libpq) required for database development. Choose the command appropriate for your Ubuntu version. ```bash sudo apt-get install postgresql-server-dev-all ``` ```bash sudo apt-get install postgresql-all ``` ```bash sudo apt-get install postgresql-all ``` ```bash sudo pacman -S postgresql ``` ```bash yum install postgresql-devel ``` ```bash brew install postgresql ``` ```bash libpq/13.4 ``` -------------------------------- ### Windows vcpkg Installation - Bootstrap vcpkg Source: https://github.com/drogonframework/drogon/wiki/CHN/CHN-02-安装 Install vcpkg, a C++ package manager, by cloning the repository and running the bootstrap script. Add vcpkg to your system's PATH. ```shell git clone https://github.com/microsoft/vcpkg cd vcpkg ./bootstrap-vcpkg.bat ``` -------------------------------- ### Install Drogon CTL Executables Source: https://github.com/drogonframework/drogon/blob/master/drogon_ctl/CMakeLists.txt Installs the drogon_ctl and _drogon_ctl executables to the specified runtime destination directory. ```cmake message(STATUS "bin:" ${INSTALL_BIN_DIR}) install(TARGETS _drogon_ctl RUNTIME DESTINATION ${INSTALL_BIN_DIR}) install(TARGETS drogon_ctl RUNTIME DESTINATION ${INSTALL_BIN_DIR}) ``` -------------------------------- ### Install Git, GCC, Make, and CMake on Arch Linux Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs essential build tools for Drogon on Arch Linux. ```shell sudo pacman -S git gcc make cmake ``` -------------------------------- ### Windows vcpkg Installation - Install Drogon Source: https://github.com/drogonframework/drogon/wiki/CHN/CHN-02-安装 Install Drogon using vcpkg commands. Specify architecture (32-bit or 64-bit) and desired features. Use 'vcpkg install ' for missing packages. ```shell vcpkg install drogon ``` ```shell vcpkg install drogon:x64-windows ``` ```shell vcpkg install jsoncpp:x64-windows zlib:x64-windows openssl:x64-windows sqlite3:x64-windows libpq:x64-windows libpqxx:x64-windows drogon[core,ctl,sqlite3,postgres,orm]:x64-windows ``` ```shell vcpkg install zlib ``` ```shell vcpkg install zlib:x64-windows ``` ```shell vcpkg install drogon[ctl] ``` ```shell vcpkg install drogon[ctl]:x64-windows ``` -------------------------------- ### Windows Source Installation - Download and Dependencies Source: https://github.com/drogonframework/drogon/wiki/CHN/CHN-02-安装 Steps to download Drogon source code and install dependencies using Conan on Windows. Ensure Conan is installed and configured. ```shell cd $WORK_PATH git clone https://github.com/drogonframework/drogon cd drogon git submodule update --init ``` ```dos mkdir build cd build conan profile detect --force conan install .. -s compiler="msvc" -s compiler.version=193 -s compiler.cppstd=17 -s build_type=Debug --output-folder . --build=missing ``` -------------------------------- ### Drogon Application Setup with Config File Source: https://github.com/drogonframework/drogon/blob/master/README.md A simplified Drogon application setup that loads configuration from a JSON file. Ensure 'config.json' exists in the application's root directory. ```C++ #include using namespace drogon; int main() { app().loadConfigFile("./config.json").run(); } ``` -------------------------------- ### Install jsoncpp on MacOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the JSON C++ library on MacOS using Homebrew. ```shell brew install jsoncpp ``` -------------------------------- ### Basic HTTP Controller Example Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/a-directory/page.html Implement a simple HTTP controller to handle requests and return an HTML response. This is suitable for basic web pages. ```c++ #include "TestCtrl.h" void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req, const std::function & callback) { //write your application logic here auto resp = HttpResponse::newHttpResponse(); resp->setBody("

Hello, world!

"); resp->setExpiredTime(0); callback(resp); } ``` -------------------------------- ### Install uuid on Arch Linux Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the UUID library on Arch Linux. ```shell sudo pacman -S uuid ``` -------------------------------- ### Install zlib Development Files on CentOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the zlib compression library development files on CentOS 7.5. ```shell yum install zlib-devel ``` -------------------------------- ### Install OpenSSL Development Files on Ubuntu (Optional) Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs OpenSSL development files to enable HTTPS support in Drogon on Ubuntu. ```shell sudo apt install openssl libssl-dev ``` -------------------------------- ### Install MariaDB Development Libraries for MySQL Support Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the MariaDB development library, which Drogon uses for MySQL support due to its asynchronous read/write capabilities. Avoid installing both MySQL and MariaDB simultaneously. ```bash sudo apt install libmariadbclient-dev ``` ```bash sudo apt install libmariadb-dev-compat libmariadb-dev ``` ```bash sudo pacman -S mariadb ``` ```bash yum install mariadb-devel ``` ```bash brew install mariadb ``` ```bash libmariadb/3.1.13 ``` -------------------------------- ### Basic Drogon Application Setup Source: https://github.com/drogonframework/drogon/blob/master/README.md This is the main program for a typical Drogon application. It configures logging, port, and thread count before running. ```C++ #include using namespace drogon; int main() { app().setLogPath("./") .setLogLevel(trantor::Logger::kWarn) .addListener("0.0.0.0", 80) .setThreadNum(16) .enableRunAsDaemon() .run(); } ``` -------------------------------- ### Linux Source Installation Source: https://github.com/drogonframework/drogon/wiki/CHN/CHN-02-安装 Compile and install Drogon from source on Linux systems. Ensure system environment and dependencies are prepared before running. ```shell cd $WORK_PATH git clone https://github.com/drogonframework/drogon cd drogon git submodule update --init mkdir build cd build cmake .. make && sudo make install ``` ```shell cmake -DCMAKE_BUILD_TYPE=Release .. ``` -------------------------------- ### Install jsoncpp Development Files on Ubuntu Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the JSON C++ library development files required by Drogon on Ubuntu. ```shell sudo apt install libjsoncpp-dev ``` -------------------------------- ### Install Drogon via vcpkg (Windows) Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Install Drogon and its features using vcpkg on Windows. Supports 32-bit, 64-bit, and specific feature sets like 'ctl', 'sqlite3', 'postgres', and 'orm'. ```shell vcpkg install drogon ``` ```shell vcpkg install drogon:x64-windows ``` ```shell vcpkg install jsoncpp:x64-windows zlib:x64-windows openssl:x64-windows sqlite3:x64-windows libpq:x64-windows libpqxx:x64-windows drogon[core,ctl,sqlite3,postgres,orm]:x64-windows ``` ```shell vcpkg install drogon[ctl] ``` ```shell vcpkg install drogon[ctl]:x64-windows ``` ```shell vcpkg search drogon ``` -------------------------------- ### Verify Drogon Installation via vcpkg Source: https://github.com/drogonframework/drogon/wiki/CHN/CHN-02-安装 Verify Drogon installation by checking the output of the drogon_ctl command in PowerShell. Ensure the command displays usage information. ```shell drogon_ctl ``` -------------------------------- ### Install OpenSSL on Arch Linux (Optional) Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs OpenSSL to enable HTTPS support in Drogon on Arch Linux. ```shell sudo pacman -S openssl libssl ``` -------------------------------- ### Install CMake from Source on CentOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs a recent version of CMake from source on CentOS 7.5, as the default version may be too low. ```shell git clone https://github.com/Kitware/CMake cd CMake/ ./bootstrap && make && make install ``` -------------------------------- ### JSON Response Controller Example Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/a-directory/page.html Create a controller that returns a JSON response. Use this for building APIs that serve data in JSON format. ```c++ #pragma once #include using namespace drogon; class JsonCtrl : public drogon::HttpSimpleController { public: void asyncHandleHttpRequest(const HttpRequestPtr &req, const std::function &callback) override; PATH_LIST_BEGIN //list path definitions here; PATH_ADD("/json", Get); PATH_LIST_END }; ``` ```c++ #include "JsonCtrl.h" void JsonCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req, const std::function &callback) { Json::Value ret; ret["message"] = "Hello, World!"; auto resp = HttpResponse::newHttpJsonResponse(ret); callback(resp); } ``` -------------------------------- ### HttpSimpleController Example Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/a-directory/page.html Defines a simple HTTP controller class that inherits from `HttpSimpleController`. This is the recommended approach for more complex business logic. ```cpp #pragma once #include using namespace drogon; class TestCtrl:public drogon::HttpSimpleController { public: virtual void asyncHandleHttpRequest(const HttpRequestPtr& req,const std::function & callback)override; PATH_LIST_BEGIN PATH_ADD("/test",Get); PATH_LIST_END }; ``` -------------------------------- ### JSON Response Controller Source: https://github.com/drogonframework/drogon/blob/master/README.md Example of a controller that returns a JSON response. It inherits from HttpSimpleController and defines a handler for the '/json' GET path. ```APIDOC ## JSON Response Controller ### Description Creates a controller that returns a JSON formatted response. ### Header File ```cpp #pragma once #include using namespace drogon; class JsonCtrl : public drogon::HttpSimpleController { public: void asyncHandleHttpRequest(const HttpRequestPtr &req, std::function &&callback) override; PATH_LIST_BEGIN //list path definitions here; PATH_ADD("/json", Get); PATH_LIST_END }; ``` ### Source File ```cpp #include "JsonCtrl.h" void JsonCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req, std::function &&callback) { Json::Value ret; ret["message"] = "Hello, World!"; auto resp = HttpResponse::newHttpJsonResponse(ret); callback(resp); } ``` ``` -------------------------------- ### Registering a Handler Directly Source: https://github.com/drogonframework/drogon/blob/master/README.md Example of registering an HTTP handler directly in the main function for a simple GET request. This is suitable for very simple logic. ```C++ app().registerHandler("/test?username={name}", [](const HttpRequestPtr& req, std::function &&callback, const std::string &name) { Json::Value json; json["result"]="ok"; json["message"]=std::string("hello,")+name; auto resp=HttpResponse::newHttpJsonResponse(json); callback(resp); }, {Get,"LoginFilter"}); ``` -------------------------------- ### Full JSONStore Example Workflow Source: https://github.com/drogonframework/drogon/blob/master/examples/jsonstore/README.md This script demonstrates a complete workflow: generating a token, creating data, retrieving a value, updating data, attempting to retrieve a non-existent value, and finally deleting the data. It uses environment variables for the URL and token. ```bash export URL="http://localhost:8848" export TOKEN=`curl $URL/get-token -s | sed 's/.*"\([0-9a-f]*\)".*/\1/'` printf "Token is: $TOKEN\n" printf 'Creating new data \n> ' curl -XPOST $URL/$TOKEN -H 'content-type: application/json' -d '{"foo":{"bar":42}}' printf '\nRetrieving value of data["foo"]["bar"] \n> ' curl $URL/$TOKEN/foo/bar printf '\nModifing data \n> ' curl -XPUT $URL/$TOKEN/foo -H 'content-type: application/json' -d '{"zoo":"zebra"}' printf '\nNow data["foo"]["bar"] no longer exists \n> ' curl $URL/$TOKEN/foo/bar printf '\nDelete data \n> ' curl -XDELETE $URL/$TOKEN echo ``` -------------------------------- ### Nix Shell Configuration for Drogon Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Use this shell.nix file to set up a development environment with Drogon and its dependencies installed via Nix. Enter the shell with 'nix-shell'. ```nix { pkgs ? import {} }: pkgs.mkShell { nativeBuildInputs = with pkgs; [ cmake ]; buildInputs = with pkgs; drogon ]; } ``` -------------------------------- ### Load Configuration from File Source: https://context7.com/drogonframework/drogon/llms.txt Loads application configuration from a JSON or YAML file at startup. This allows customization of listeners, database clients, sessions, and logging without recompiling. ```cpp #include int main() { // config.json (minimal example): // { // "listeners": [{"address":"0.0.0.0","port":8080}], // "app": { "threads_num": 8, "enable_session": true, "session_timeout": 1200 }, // "db_clients": [{"rdbms":"postgresql","host":"127.0.0.1","port":5432, // "dbname":"mydb","user":"admin","passwd":"secret", // "connection_number":5}], // "log": { "log_path":"./","log_level":"INFO" } // } drogon::app().loadConfigFile("./config.json").run(); } ``` -------------------------------- ### Drogon ctl Create Command Help Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-12-drogon_ctl-Command Displays the help message for the 'create' subcommand, outlining its usage and available options for generating different project components. ```console $ dg_ctl help create Use create command to create some source files of drogon webapp Usage:drogon_ctl create [-options] drogon_ctl create view [-o ] [-n ]|[--path-to-namespace] //create HttpView source files from csp file drogon_ctl create controller [-s] <[namespace::]class_name> //create HttpSimpleController source files drogon_ctl create controller -h <[namespace::]class_name> //create HttpController source files drogon_ctl create controller -w <[namespace::]class_name> //create WebSocketController source files drogon_ctl create filter <[namespace::]class_name> //create a filter named class_name drogon_ctl create project //create a project named project_name drogon_ctl create model //create model classes in model_path ``` -------------------------------- ### Registering a Handler Directly Source: https://github.com/drogonframework/drogon/blob/master/README.md This example shows how to register a handler directly in the main() function using drogon::app().registerHandler(). It includes a GET request handler for a path with a query parameter. ```APIDOC ## Register Handler ### Description Registers a handler function for a specific URI with optional filters. ### Method ```APIDOC app().registerHandler(uri, handler, filters) ``` ### Parameters - **uri**: The URI path, which can include named parameters (e.g., "/test?username={name}"). - **handler**: A lambda function or callable that handles the request. - **filters**: A list of filters to apply to the handler. ### Request Example ```cpp app().registerHandler("/test?username={name}", [](const HttpRequestPtr& req, std::function &&callback, const std::string &name) { Json::Value json; json["result"]="ok"; json["message"]=std::string("hello,")+name; auto resp=HttpResponse::newHttpJsonResponse(json); callback(resp); }, {Get,"LoginFilter"}); ``` ``` -------------------------------- ### Create RESTful API Controller in Drogon Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/index.html Utilize `HttpController` to create RESTful APIs, mapping paths and parameters simultaneously. This example defines handlers for GET and POST requests with path parameters. ```c++ #pragma once #include using namespace drogon; namespace api { namespace v1 { class User : public drogon::HttpController { public: METHOD_LIST_BEGIN //use METHOD_ADD to add your custom processing function here; METHOD_ADD(User::getInfo, "/{1}", Get); //path is /api/v1/User/{arg1} METHOD_ADD(User::getDetailInfo, "/{1}/detailinfo", Get); //path is /api/v1/User/{arg1}/detailinfo METHOD_ADD(User::newUser, "/{1}", Post); //path is /api/v1/User/{arg1} METHOD_LIST_END //your declaration of processing function maybe like this: void getInfo(const HttpRequestPtr &req, const std::function &callback, int userId) const; void getDetailInfo(const HttpRequestPtr &req, const std::function &callback, int userId) const; void newUser(const HttpRequestPtr &req, const std::function &callback, std::string &&userName); public: User() { LOG_DEBUG << "User constructor!"; } }; } // namespace v1 } // namespace api ``` -------------------------------- ### Basic Drogon Application Setup Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/index.html This snippet shows the minimal configuration for a Drogon application, including setting log paths, log levels, listening addresses, thread numbers, and running as a daemon. ```c++ #include using namespace drogon; int main() { app().setLogPath("./"); app().setLogLevel(trantor::Logger::kWarn); app().addListener("0.0.0.0", 80); app().setThreadNum(16); app().enableRunAsDaemon(); app().run(); } ``` -------------------------------- ### Get Request Parameter (GET) Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-09-0-References-request Retrieve a parameter value from a GET request using its key. The result is a string, which may need conversion. ```c++ #include "mycontroller.h" #include using namespace drogon; void mycontroller::anyhandle(const HttpRequestPtr &req, std::function &&callback) { // https://mysite.com/an-path/?id=5 std::string id = req->getParameter("id"); // or long id = std::strtol(req->getParameter("id")); } ``` -------------------------------- ### Install GCC on CentOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the GCC C++ compiler on CentOS 7.5. ```shell yum install gcc ``` ```shell yum install gcc-c++ ``` -------------------------------- ### Install ossp-uuid on MacOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the OSSP UUID library on MacOS using Homebrew. ```shell brew install ossp-uuid ``` -------------------------------- ### Install libuuid Development Files on CentOS Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the library for generating UUIDs on CentOS 7.5. ```shell yum install libuuid-devel ``` -------------------------------- ### Create Drogon Project Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-03-Quick-Start Use the `drogon_ctl` command-line tool to generate a new Drogon web application project structure. This command initializes the necessary files and directories for your project. ```shell drogon_ctl create project your_project_name ``` -------------------------------- ### Drogon Application Main Function Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-03-Quick-Start The `main.cc` file contains the entry point for the Drogon application. It demonstrates how to set the listener address and port, load configuration, and start the HTTP framework. The `run()` method blocks and enters the event loop. ```c++ #include int main() { //Set HTTP listener address and port drogon::app().addListener("0.0.0.0",80); //Load config file //drogon::app().loadConfigFile("../config.json"); //Run HTTP framework,the method will block in the internal event loop drogon::app().run(); return 0; } ``` -------------------------------- ### Create HttpSimpleController Source Files Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-12-drogon_ctl-Command Creates HttpSimpleController source files. The last parameter is the controller's class name, which can optionally be prefixed by a namespace. ```shell dg_ctl create controller SimpleControllerTest ``` ```shell dg_ctl create controller webapp::v1::SimpleControllerTest ``` -------------------------------- ### Install OpenSSL on MacOS (Optional) Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs OpenSSL to enable HTTPS support in Drogon on MacOS using Homebrew. ```shell brew install openssl ``` -------------------------------- ### Create WebSocketController Source Files Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-12-drogon_ctl-Command Creates WebSocketController source files using the '-w' flag followed by the controller's class name, which can include a namespace. ```shell dg_ctl create controller -w WsControllerTest ``` ```shell dg_ctl create controller -w api::v1::WsControllerTest ``` -------------------------------- ### Drogon CMakeLists.txt Setup Source: https://context7.com/drogonframework/drogon/llms.txt Configure your project to use Drogon by finding the package, adding your executable, and linking against the Drogon library. Use 'make test' to run CTest cases. ```cmake find_package(Drogon REQUIRED) add_executable(tests test_main.cc) target_link_libraries(tests PRIVATE Drogon::Drogon) ParseAndAddDrogonTests(tests) ``` -------------------------------- ### Create Plugin using drogon_ctl Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-10-Plugins Command-line instruction to generate the boilerplate source files for a new Drogon plugin using the `drogon_ctl` utility. ```shell drogon_ctl create plugin <[namespace::]class_name> ``` -------------------------------- ### Install OpenSSL Development Files on CentOS (Optional) Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs OpenSSL development files to enable HTTPS support in Drogon on CentOS 7.5. ```shell yum install openssl-devel ``` -------------------------------- ### Render CSP View with Parameters Source: https://context7.com/drogonframework/drogon/llms.txt Handles HTTP requests, prepares data, and renders a CSP view. Ensure the view file exists and data keys match view variables. ```cpp // Handler in a controller: void PageCtrl::asyncHandleHttpRequest( const HttpRequestPtr &req, std::function &&callback) { auto params = req->getParameters(); HttpViewData data; data.insert("title", "Parameter List"); data.insert("parameters", params); callback(HttpResponse::newHttpViewResponse("ListParams.csp", data)); } ``` ```html <%c++ auto params = @@.get>("parameters"); %> [[ title ]] <%c++ if (!params.empty()) { %> <%c++ for (auto &kv : params) { %> <%c++ } %>
KeyValue
{%kv.first%}{%kv.second%}
<%c++ } else { %>

No parameters.

<%c++ } %> ``` -------------------------------- ### HttpController with Regex Path Mapping Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-04-2-Controller-HttpController Demonstrates using regular expressions within path mappings for more flexible route matching. The first example matches any path prefixed with `/users/`, and the second matches paths with a name string followed by a number. ```cpp ADD_METHOD_TO(UserController::handler1,"/users/.*",Post); /// Match any path prefixed with `/users/` ADD_METHOD_TO(UserController::handler2,"/{name}/[0-9]+",Post); ///Match any path composed with a name string and a number. ``` -------------------------------- ### Install Conan Package Manager via Pip Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Installs the Conan C/C++ package manager using pip, which is useful for managing Drogon dependencies on Windows. ```shell pip install conan ``` -------------------------------- ### Create Static HTML File Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-03-Quick-Start A simple command to create an `index.html` file with basic HTML content. This file will be served by the Drogon application if placed in the HTTP root path. ```shell echo '

Hello Drogon!

' >>index.html ``` -------------------------------- ### Configure Supported File Types Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-11-Configuration-File An array of file extensions that the framework will serve as static files. Requests for other extensions result in a 404 error. ```json "file_types": [ "gif", "png", "jpg", "js", "css", "html", "ico", "swf", "xap", "apk", "cur", "xml" ], ``` -------------------------------- ### Nix Package Override Example Source: https://github.com/drogonframework/drogon/wiki/CHN/CHN-02-安装 Example of overriding Drogon's Nix package options, such as disabling SQLite support. Adjust buildInputs to include the overridden package. ```nix buildInputs = with pkgs; [ (drogon.override { sqliteSupport = false; }) ]; ``` -------------------------------- ### TestCtrl.cc with 'Hello World!' Response Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-03-Quick-Start The controller's source file is modified to create and send an HTTP response. It sets the status code to 200 OK, content type to HTML, and the body to 'Hello World!'. ```c++ #include "TestCtrl.h" void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req, std::function &&callback) { //write your application logic here auto resp=HttpResponse::newHttpResponse(); //NOTE: The enum constant below is named "k200OK" (as in 200 OK), not "k2000K". resp->setStatusCode(k200OK); resp->setContentTypeCode(CT_TEXT_HTML); resp->setBody("Hello World!"); callback(resp); } ``` -------------------------------- ### Install Drogon Dependencies (Windows with Conan) Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-02-Installation Install Drogon dependencies using Conan on Windows. This command configures Conan for MSVC, specifies C++ standard, and builds missing packages. ```dos mkdir build cd build conan profile detect --force conan install .. -s compiler="msvc" -s compiler.version=193 -s compiler.cppstd=17 -s build_type=Debug --output-folder . --build=missing ``` -------------------------------- ### Create Drogon Project Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-12-drogon_ctl-Command Initializes a new Drogon application project. After execution, a project directory is created in the current location, ready for compilation. ```shell dg_ctl create project ProjectName ``` -------------------------------- ### Display Drogon Version Information Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-12-drogon_ctl-Command Execute 'dg_ctl version' to display the currently installed Drogon framework version, Git commit hash, and compilation configuration. This is useful for verifying installation and debugging. ```console $ dg_ctl version _ __| |_ __ ___ __ _ ___ _ __ / _` | '__/ _ \ / _` |/ _ \| '_ \ | (_| | | | (_) | (_| | (_) | | | | \__,_|_| \___/ \__, |\___/|_| |_| |___/ drogon ctl tools version:0.9.30.771 git commit:d4710d3da7ca9e73b881cbae3149c3a570da8de4 compile config:-O3 -DNDEBUG -Wall -std=c++17 -I/root/drogon/trantor -I/root/drogon/lib/inc -I/root/drogon/orm_lib/inc -I/usr/local/include -I/usr/include/uuid -I/usr/include -I/usr/include/mysql ``` -------------------------------- ### DbClient Asynchronous SQL Execution with Future Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-08-1-Database-DbClient Executes SQL asynchronously and returns a std::future for retrieving the result. The caller blocks only when calling the `get` method on the future. May throw exceptions when `get` is called. ```c++ template std::future execSqlAsyncFuture(const std::string &sql, Arguments &&... args) noexcept; ``` -------------------------------- ### Start Drogon Event Loop for Tests Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-19-Testing-Framework This boilerplate code ensures Drogon's event loop is running before tests begin, which is necessary for components like HTTP clients. It starts the loop in a separate thread and synchronizes its startup. ```c++ int main() { std::promise p1; std::future f1 = p1.get_future(); // Start the main loop on another thread std::thread thr([&]() { // Queues the promise to be fulfilled after starting the loop app().getLoop()->queueInLoop([&p1]() { p1.set_value(); }); app().run(); }); // The future is only satisfied after the event loop started f1.get(); int status = test::run(argc, argv); // Ask the event loop to shutdown and wait app().getLoop()->queueInLoop([]() { app().quit(); }); thr.join(); return status; } ``` -------------------------------- ### Implementing a Simple HTTP Controller in Drogon Source: https://github.com/drogonframework/drogon/blob/master/lib/tests/integration_test/server/index.html Provides an example of creating a custom HTTP controller by inheriting from HttpSimpleController. This demonstrates defining a handler for a specific path and HTTP method. ```c++ #pragma once #include using namespace drogon; class TestCtrl:public drogon::HttpSimpleController { public: virtual void asyncHandleHttpRequest(const HttpRequestPtr& req,const std::function & callback)override; PATH_LIST_BEGIN PATH_ADD("/test",Get); PATH_LIST_END }; ``` ```c++ #include "TestCtrl.h" void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req, const std::function & callback) { //write your application logic here auto resp = HttpResponse::newHttpResponse(); resp->setBody("

Hello, world!

"); resp->setExpiredTime(0); callback(resp); } ``` -------------------------------- ### Get Request Path Source: https://github.com/drogonframework/drogon/wiki/ENG/ENG-09-0-References-request Retrieve the request path using getPath(). Useful for dynamic URL routing. ```c++ #include "mycontroller.h" #include using namespace drogon; void mycontroller::anyhandle(const HttpRequestPtr &req, std::function &&callback) { // https://mysite.com/an-path/?id=5 std::string url = req->getPath(); // url = /an-path/ } ``` -------------------------------- ### Bootstrap Drogon Application Source: https://context7.com/drogonframework/drogon/llms.txt Starts a Drogon application using the HttpAppFramework singleton. Configure listeners, logging, and thread count before running. The run() method blocks until the application exits. ```cpp #include using namespace drogon; int main() { app().setLogPath("./") .setLogLevel(trantor::Logger::kWarn) .addListener("0.0.0.0", 8080) .setThreadNum(16) // IO threads; 0 = number of hardware cores .enableRunAsDaemon() .run(); // blocks until app exits } ```