drogon README

The project's README from github.com/drogonframework/drogon. As one markdown file: README.md.

Build Status Conan Center Join the telegram group at https://t.me/joinchat/_mMNGv0748ZkMDAx Join our Discord Docker image

English | 简体中文 | 繁體中文

Overview

Drogon is a C++17/20 based HTTP application framework. Drogon can be used to easily build various types of web application server programs using C++. Drogon is the name of a dragon from the American TV series Game of Thrones, which I really enjoy.

Drogon is a cross-platform framework, It supports Linux, macOS, FreeBSD, OpenBSD, HaikuOS, and Windows. Its main features are as follows:

A very simple example

Unlike most C++ frameworks, the main program of the drogon application can be kept clean and simple. Drogon uses a few tricks to decouple controllers from the main program. The routing settings of controllers can be done through macros or configuration file.

Below is the main program of a typical drogon application:

#include <drogon/drogon.h>

using namespace drogon;

int main()
{
    app().setLogPath("./")
         .setLogLevel(trantor::Logger::kWarn)
         .addListener("0.0.0.0", 80)
         .setThreadNum(16)
         .enableRunAsDaemon()
         .run();
}

It can be further simplified by using configuration file as follows:

#include <drogon/drogon.h>

using namespace drogon;

int main()
{
    app().loadConfigFile("./config.json").run();
}

Drogon provides some interfaces for adding controller logic directly in the main() function, for example, user can register a handler like this in Drogon:

app().registerHandler("/test?username={name}",
                    [](const HttpRequestPtr& req,
                       std::function<void (const HttpResponsePtr &)> &&callback,
                       const std::string &name) -> void
                    {
                        Json::Value json;
                        json["result"] = "ok";
                        json["message"] = "hello, " + name;
                        HttpResponsePtr resp = HttpResponse::newHttpJsonResponse(json);
                        callback(resp);
                    },
                    {Get,"LoginFilter"});

While such interfaces look intuitive, they are not suitable for complex business logic scenarios. Assuming there are tens or even hundreds of handlers that need to be registered in the framework, isn't it a better practice to implement them separately in their respective classes? So unless your logic is very simple, we don't recommend using above interfaces. Instead, we can create an HttpSimpleController as follows:

/// The TestCtrl.h file
#pragma once
#include <drogon/HttpSimpleController.h>

using namespace drogon;

class TestCtrl : public HttpSimpleController<TestCtrl>
{
public:
    void asyncHandleHttpRequest(const HttpRequestPtr& req, std::function<void (const HttpResponsePtr &)> &&callback) override;
    PATH_LIST_BEGIN
    PATH_ADD("/test",Get);
    PATH_LIST_END
};

/// The TestCtrl.cc file
#include "TestCtrl.h"

void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req,
                                      std::function<void (const HttpResponsePtr &)> &&callback)
{
    // write your application logic here
    HttpResponsePtr resp = HttpResponse::newHttpResponse();
    resp->setBody("<p>Hello, world!</p>");
    resp->setExpiredTime(0);
    callback(resp);
}

Most of the above programs can be automatically generated by the command line tool drogon_ctl provided by drogon (The command is drogon_ctl create controller TestCtrl). All the user needs to do is add their own business logic. In the example, the controller returns a Hello, world! string when the client accesses the http://ip/test URL.

For JSON format response, we create the controller as follows:

/// The header file
#pragma once

#include <drogon/HttpSimpleController.h>

using namespace drogon;

class JsonCtrl : public HttpSimpleController<JsonCtrl>
{
  public:
    void asyncHandleHttpRequest(const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback) override;
    PATH_LIST_BEGIN
    // list path definitions here;
    PATH_ADD("/json", Get);
    PATH_LIST_END
};

/// The source file
#include "JsonCtrl.h"

void JsonCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req,
                                      std::function<void(const HttpResponsePtr &)> &&callback)
{
    Json::Value ret;
    ret["message"] = "Hello, World!";
    HttpResponsePtr resp = HttpResponse::newHttpJsonResponse(ret);
    callback(resp);
}

Let's go a step further and create a demo RESTful API with the HttpController class, as shown below (Omit the source file):

/// The header file
#pragma once
#include <drogon/HttpController.h>

using namespace drogon;

namespace api::v1
{
class User : public HttpController<User>
{
  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<void(const HttpResponsePtr &)> &&callback, int userId) const;
    void getDetailInfo(const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback, int userId) const;
    void newUser(const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback, std::string &&userName);
  public:
    User()
    {
        LOG_DEBUG << "User constructor!";
    }
};
} // namespace api::v1

As you can see, users can use the HttpController to map paths and parameters at the same time. This is a very convenient way to create a RESTful API application.

In addition, you can also find that all handler interfaces are in asynchronous mode, where the response is returned by a callback object. This design is for performance reasons because in asynchronous mode the drogon application can handle a large number of concurrent requests with a small number of threads.

After compiling all of the above source files, we get a very simple web application. This is a good start. For more information, please visit the documentation on GitHub.

Cross-compilation

Drogon supports cross-compilation, you should define the CMAKE_SYSTEM_NAME in toolchain file, for example:

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

You can disable building options for examples and drogon_ctl by settings BUILD_EXAMPLES and BUILD_CTL to OFF in the toolchain file.

Building options

Drogon provides some building options, you can enable or disable them by setting the corresponding variables to ON or OFF in the cmake command line, cmake file etc...

Option name Description Default value
BUILD_CTL Build drogon_ctl ON
BUILD_EXAMPLES Build examples ON
BUILD_ORM Build orm ON
COZ_PROFILING Use coz for profiling OFF
BUILD_SHARED_LIBS Build drogon as a shared lib OFF
BUILD_DOC Build Doxygen documentation OFF
BUILD_BROTLI Build Brotli ON
BUILD_YAML_CONFIG Build yaml config ON
USE_SUBMODULE Use trantor as a submodule ON

Contributions

This project exists thanks to all the people who contribute code.

Code contributors

Every contribution is welcome. Please refer to the contribution guidelines for more information.

drogon (drogonframework/drogon)

Searching Database…

14.3K ·GitHub
Что это такое?Drogon — открытый HTTP-фреймворк на C++14/17/20 под лицензией MIT для создания веб-приложений на C++ — от REST API до сайтов с рендерингом на сервере и приложений на WebSocket.
Это полноценный фреймворк, на котором я построю всё приложение, или скорее библиотека?Полноценный веб-фреймворк, а не тонкая библиотека: неблокирующие HTTP-сервер и клиент, маршрутизация, сессии, шаблоны CSP, ORM, асинхронные клиенты для баз данных и Redis, плагины, а также утилита командной строки drogonctl.
Как запустить первое приложение?Создайте каркас кода через drogonctl ('drogonctl create controller TestCtrl'), добавьте свою бизнес-логику и соберите проект с помощью CMake. Контроллеры привязываются к маршрутам через макросы или файл конфигурации, поэтому main() остаётся чистым.
Что нужно установить, чтобы собрать проект?Инструменты для C++ и CMake: сборка идёт из исходников, функции включаются опциями CMake (ORM, Brotli, YAML-конфигурация, drogonctl). Сетевая библиотека trantor по умолчанию подключается как сабмодуль, а для HTTPS нужен OpenSSL.
Можно спокойно держать весь код обработчиков в main(), или есть подвох?Регистрацию обработчиков прямо в main() авторы рекомендуют только для очень простой логики — для настоящих приложений README советует выносить их в отдельные классы контроллеров.
Он в основном для REST API или умеет и страницы с рендерингом на сервере?Веб-бэкенды любых типов: работа с JSON-запросами и ответами очень удобна для RESTful API, шаблоны CSP закрывают HTML с рендерингом на сервере, а WebSocket, загрузка и скачивание файлов, gzip/brotli и pipelining уже встроены.
На каких операционных системах он работает?Linux, macOS, FreeBSD, OpenBSD, HaikuOS и Windows, включая ARM, с кросс-компиляцией через toolchain-файл CMake. Сетевой ввод-вывод использует epoll, а на macOS/FreeBSD — kqueue, что даёт высокую производительность при большом числе одновременных подключений.
Обработчики обязательно писать в стиле колбэков или современный C++ тоже поддерживается?Классические обработчики возвращают ответ через колбэк — такой асинхронный дизайн позволяет небольшому числу потоков обслуживать множество одновременных запросов. Поддерживаются и C++-корутины как более современный стиль.
С какими базами данных он умеет работать?PostgreSQL и MySQL/MariaDB через неблокирующие асинхронные клиенты, sqlite3 — асинхронно через пул потоков, плюс Redis — всё доступно через лёгкий ORM с двусторонним отображением объектов в базу данных.
Есть ли что-то вроде middleware для общей логики, например проверки входа?Да — цепочки фильтров выполняют общую логику (проверку авторизации, ограничения HTTP-методов) до того, как запрос попадёт в обработчики, плагины загружаются из файла конфигурации при старте, а также поддерживается AOP со встроенными joinpoint.
Почему фреймворк называется Drogon?Он назван в честь дракона из сериала «Игра престолов», который автору очень нравится.
What are similar projects?Perfect, carno.js, webserver, cpp-httplib, aiohttp, sails, go-zero, echo
Size
6.5 MB
Stars
14.3K
Age
8y
Commits · 90 Days