merged AI doc, some new pages
This commit is contained in:
@@ -1,3 +1,27 @@
|
||||
//! \~\file microhttpd_server.h
|
||||
//! \~\ingroup HTTP
|
||||
//! \~\brief
|
||||
//! \~english Base HTTP server API built on top of libmicrohttpd
|
||||
//! \~russian Базовый API HTTP-сервера, построенный поверх libmicrohttpd
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Base HTTP server API built on top of libmicrohttpd
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MICROHTTPD_SERVER_P_H
|
||||
#define MICROHTTPD_SERVER_P_H
|
||||
|
||||
@@ -7,85 +31,92 @@
|
||||
|
||||
struct MicrohttpdServerConnection;
|
||||
|
||||
//! \~english Base HTTP server class implementing core functionality
|
||||
//! \~russian Базовый класс HTTP сервера, реализующий основную функциональность
|
||||
//! \~\ingroup HTTP
|
||||
//! \~\brief
|
||||
//! \~english Base HTTP server with request dispatch and optional basic authentication.
|
||||
//! \~russian Базовый HTTP-сервер с диспетчеризацией запросов и необязательной basic-аутентификацией.
|
||||
class PIP_HTTP_SERVER_EXPORT MicrohttpdServer: public PIObject {
|
||||
PIOBJECT(MicrohttpdServer)
|
||||
friend struct MicrohttpdServerConnection;
|
||||
|
||||
public:
|
||||
//! \~english Creates a stopped server instance with default options.
|
||||
//! \~russian Создает остановленный экземпляр сервера с настройками по умолчанию.
|
||||
MicrohttpdServer();
|
||||
//! \~english Stops the server and releases native resources.
|
||||
//! \~russian Останавливает сервер и освобождает нативные ресурсы.
|
||||
virtual ~MicrohttpdServer();
|
||||
|
||||
//! \~english Server configuration options
|
||||
//! \~russian Опции конфигурации сервера
|
||||
//! \~english Server configuration options accepted by \a setOption().
|
||||
//! \~russian Параметры конфигурации сервера, принимаемые методом \a setOption().
|
||||
enum class Option {
|
||||
ConnectionLimit, //!< \~english Maximum concurrent connections
|
||||
//!< \~russian Максимальное количество соединений
|
||||
ConnectionTimeout, //!< \~english Connection timeout in seconds
|
||||
//!< \~russian Таймаут соединения в секундах
|
||||
HTTPSEnabled, //!< \~english Enable HTTPS support
|
||||
//!< \~russian Включить поддержку HTTPS
|
||||
HTTPSMemKey, //!< \~english SSL key in memory (PIByteArray)
|
||||
//!< \~russian SSL ключ в памяти (PIByteArray)
|
||||
HTTPSMemCert, //!< \~english SSL certificate in memory (PIByteArray)
|
||||
//!< \~russian SSL сертификат в памяти (PIByteArray)
|
||||
HTTPSKeyPassword //!< \~english SSL key password (PIByteArray)
|
||||
//!< \~russian Пароль SSL ключа (PIByteArray)
|
||||
ConnectionLimit /** \~english Maximum number of simultaneously accepted connections. \~russian Максимальное число одновременно
|
||||
принимаемых соединений. */
|
||||
,
|
||||
ConnectionTimeout /** \~english Per-connection timeout value. \~russian Значение таймаута для отдельного соединения. */,
|
||||
HTTPSEnabled /** \~english Enables TLS mode for the daemon. \~russian Включает режим TLS для демона. */,
|
||||
HTTPSMemKey /** \~english Private key stored in memory as \c PIByteArray. \~russian Приватный ключ, хранящийся в памяти в виде \c
|
||||
PIByteArray. */
|
||||
,
|
||||
HTTPSMemCert /** \~english Certificate stored in memory as \c PIByteArray. \~russian Сертификат, хранящийся в памяти в виде \c
|
||||
PIByteArray. */
|
||||
,
|
||||
HTTPSKeyPassword /** \~english Password for the in-memory private key as \c PIByteArray. \~russian Пароль для приватного ключа в
|
||||
памяти в виде \c PIByteArray. */
|
||||
};
|
||||
|
||||
//! \~english Sets server option
|
||||
//! \~russian Устанавливает опцию сервера
|
||||
//! \~english Sets a server option. The expected variant payload depends on the selected \a Option.
|
||||
//! \~russian Устанавливает параметр сервера. Ожидаемый тип значения \c PIVariant зависит от выбранного \a Option.
|
||||
void setOption(Option o, PIVariant v);
|
||||
|
||||
//! \~english Sets server favicon
|
||||
//! \~russian Устанавливает фавикон сервера
|
||||
//! \~english Sets the bytes returned for requests to \c /favicon.ico.
|
||||
//! \~russian Устанавливает байты, возвращаемые для запросов к \c /favicon.ico.
|
||||
void setFavicon(const PIByteArray & im);
|
||||
|
||||
|
||||
//! \~english Starts server on specified address
|
||||
//! \~russian Запускает сервер на указанном адресе
|
||||
//! \~english Starts listening on the specified network address, restarting the daemon if needed.
|
||||
//! \~russian Запускает прослушивание на указанном сетевом адресе, при необходимости перезапуская демон.
|
||||
bool listen(PINetworkAddress addr);
|
||||
|
||||
//! \~english Starts server on all interfaces
|
||||
//! \~russian Запускает сервер на всех интерфейсах
|
||||
//! \~english Starts listening on all interfaces for the specified port.
|
||||
//! \~russian Запускает прослушивание на всех интерфейсах для указанного порта.
|
||||
bool listenAll(ushort port) { return listen({0, port}); }
|
||||
|
||||
//! \~english Checks if server is running
|
||||
//! \~russian Проверяет, работает ли сервер
|
||||
//! \~english Returns \c true while the native HTTP daemon is running.
|
||||
//! \~russian Возвращает \c true, пока нативный HTTP-демон запущен.
|
||||
bool isListen() const;
|
||||
|
||||
//! \~english Stops the server
|
||||
//! \~russian Останавливает сервер
|
||||
//! \~english Stops listening and shuts down the native HTTP daemon.
|
||||
//! \~russian Останавливает прослушивание и завершает работу нативного HTTP-демона.
|
||||
void stop();
|
||||
|
||||
|
||||
//! \~english Enables basic authentication
|
||||
//! \~russian Включает базовую аутентификацию
|
||||
//! \~english Enables HTTP Basic authentication checks for new requests.
|
||||
//! \~russian Включает проверки HTTP Basic-аутентификации для новых запросов.
|
||||
void enableBasicAuth() { setBasicAuthEnabled(true); }
|
||||
|
||||
//! \~english Disables basic authentication
|
||||
//! \~russian Выключает базовую аутентификацию
|
||||
//! \~english Disables HTTP Basic authentication checks.
|
||||
//! \~russian Отключает проверки HTTP Basic-аутентификации.
|
||||
void disableBasicAuth() { setBasicAuthEnabled(false); }
|
||||
|
||||
//! \~english Set basic authentication enabled to "yes"
|
||||
//! \~russian Устанавливает базовую аутентификацию в "yes"
|
||||
//! \~english Enables or disables HTTP Basic authentication checks.
|
||||
//! \~russian Включает или отключает проверки HTTP Basic-аутентификации.
|
||||
void setBasicAuthEnabled(bool yes) { use_basic_auth = yes; }
|
||||
|
||||
//! \~english Return if basic authentication enabled
|
||||
//! \~russian Возвращает включена ли базовая аутентификация
|
||||
//! \~english Returns whether HTTP Basic authentication checks are enabled.
|
||||
//! \~russian Возвращает, включены ли проверки HTTP Basic-аутентификации.
|
||||
bool isBasicAuthEnabled() const { return use_basic_auth; }
|
||||
|
||||
//! \~english Sets basic authentication realm
|
||||
//! \~russian Устанавливает область аутентификации
|
||||
//! \~english Sets the realm sent in HTTP Basic authentication challenges.
|
||||
//! \~russian Устанавливает realm, отправляемый в challenge HTTP Basic-аутентификации.
|
||||
void setBasicAuthRealm(const PIString & r) { realm = r; }
|
||||
|
||||
//! \~english Sets request processing callback
|
||||
//! \~russian Устанавливает callback для обработки запросов
|
||||
//! \~english Sets the callback that receives parsed requests and returns replies.
|
||||
//! \~russian Устанавливает callback, который получает разобранные запросы и возвращает ответы.
|
||||
void setRequestCallback(std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)> c) { callback = c; }
|
||||
|
||||
//! \~english Sets basic authentication callback
|
||||
//! \~russian Устанавливает callback для базовой аутентификации
|
||||
//! \~english Sets the credential validator used when HTTP Basic authentication is enabled.
|
||||
//! \~russian Устанавливает валидатор учетных данных, используемый при включенной HTTP Basic-аутентификации.
|
||||
void setBasicAuthCallback(std::function<bool(const PIString &, const PIString &)> c) { callback_auth = c; }
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,26 +1,67 @@
|
||||
//! \addtogroup HTTP
|
||||
//! \~\file pihttpserver.h
|
||||
//! \brief High-level HTTP server implementation
|
||||
//! \~english High-level HTTP server with path-based routing and handler registration
|
||||
//! \~russian Высокоуровневый HTTP сервер с маршрутизацией по путям и регистрацией обработчиков
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
High-level HTTP server implementation
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef PIHTTPSERVER_H
|
||||
#define PIHTTPSERVER_H
|
||||
|
||||
#include "microhttpd_server.h"
|
||||
|
||||
//! \~english HTTP server
|
||||
//! \~russian HTTP сервер
|
||||
//! \~\ingroup HTTP
|
||||
//! \~\brief
|
||||
//! \~english HTTP server that routes requests by method and path pattern.
|
||||
//! \~russian HTTP-сервер, маршрутизирующий запросы по методу и шаблону пути.
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english Registered paths are matched segment by segment. The router supports fixed segments,
|
||||
//! \c * for any single segment, \c ** for any tail, and \c {name} placeholders that populate
|
||||
//! \a PIHTTP::MessageConst::pathArguments().
|
||||
//! \~russian Зарегистрированные пути сопоставляются посегментно. Маршрутизатор поддерживает
|
||||
//! фиксированные сегменты, \c * для любого одного сегмента, \c ** для любого хвоста и
|
||||
//! заполнители \c {name}, которые заполняют \a PIHTTP::MessageConst::pathArguments().
|
||||
class PIP_HTTP_SERVER_EXPORT PIHTTPServer: public MicrohttpdServer {
|
||||
PIOBJECT_SUBCLASS(PIHTTPServer, MicrohttpdServer)
|
||||
|
||||
public:
|
||||
//! \~english Creates a server with built-in path dispatching.
|
||||
//! \~russian Создает сервер со встроенной диспетчеризацией по путям.
|
||||
PIHTTPServer();
|
||||
|
||||
//! \~english Destroys the server and stops listening if needed.
|
||||
//! \~russian Удаляет сервер и при необходимости останавливает прослушивание.
|
||||
virtual ~PIHTTPServer();
|
||||
|
||||
//! \~english Request handler used by registered routes and fallback processing.
|
||||
//! \~russian Обработчик запроса, используемый зарегистрированными маршрутами и fallback-обработкой.
|
||||
using RequestFunction = std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)>;
|
||||
|
||||
|
||||
//! \~english Registers handler for specific path and HTTP method
|
||||
//! \~russian Регистрирует обработчик для указанного пути и HTTP метода
|
||||
//! \~english Registers a handler for the specified path pattern and HTTP method.
|
||||
//! \~russian Регистрирует обработчик для указанного шаблона пути и HTTP-метода.
|
||||
bool registerPath(const PIString & path, PIHTTP::Method method, RequestFunction functor);
|
||||
|
||||
//! \~english Registers handler for specific path and HTTP method
|
||||
//! \~russian Регистрирует обработчик для указанного пути и HTTP метода
|
||||
//! \~english Registers an object method as a handler for the specified path pattern and HTTP method.
|
||||
//! \~russian Регистрирует метод объекта как обработчик для указанного шаблона пути и HTTP-метода.
|
||||
template<typename T>
|
||||
bool
|
||||
registerPath(const PIString & path, PIHTTP::Method method, T * o, PIHTTP::MessageMutable (T::*function)(const PIHTTP::MessageConst &)) {
|
||||
@@ -28,36 +69,36 @@ public:
|
||||
}
|
||||
|
||||
|
||||
//! \~english Registers handler for unregistered pathes
|
||||
//! \~russian Регистрирует обработчик для незарегистрированных путей
|
||||
//! \~english Registers a fallback handler for requests that did not match any route.
|
||||
//! \~russian Регистрирует fallback-обработчик для запросов, не совпавших ни с одним маршрутом.
|
||||
void registerUnhandled(RequestFunction functor);
|
||||
|
||||
//! \~english Registers handler for unregistered pathes
|
||||
//! \~russian Регистрирует обработчик для незарегистрированных путей
|
||||
//! \~english Registers an object method as the fallback handler for unmatched requests.
|
||||
//! \~russian Регистрирует метод объекта как fallback-обработчик для несовпавших запросов.
|
||||
template<typename T>
|
||||
void registerUnhandled(T * o, PIHTTP::MessageMutable (T::*function)(const PIHTTP::MessageConst &)) {
|
||||
registerUnhandled([o, function](const PIHTTP::MessageConst & m) { return (o->*function)(m); });
|
||||
}
|
||||
|
||||
//! \~english Unregisters handler for specific path and method
|
||||
//! \~russian Удаляет обработчик для указанного пути и метода
|
||||
//! \~english Unregisters the handler for the specified path pattern and HTTP method.
|
||||
//! \~russian Удаляет обработчик для указанного шаблона пути и HTTP-метода.
|
||||
void unregisterPath(const PIString & path, PIHTTP::Method method);
|
||||
|
||||
//! \~english Unregisters all handlers for specific path
|
||||
//! \~russian Удаляет все обработчики для указанного пути
|
||||
//! \~english Unregisters all handlers bound to the specified path pattern.
|
||||
//! \~russian Удаляет все обработчики, привязанные к указанному шаблону пути.
|
||||
void unregisterPath(const PIString & path);
|
||||
|
||||
|
||||
//! \~english Adds header to all server responses
|
||||
//! \~russian Добавляет заголовок ко всем ответам сервера
|
||||
//! \~english Adds a header that will be copied to all replies produced by this router.
|
||||
//! \~russian Добавляет заголовок, который будет копироваться во все ответы этого маршрутизатора.
|
||||
void addReplyHeader(const PIString & name, const PIString & value) { reply_headers[name] = value; }
|
||||
|
||||
//! \~english Removes header from server responses
|
||||
//! \~russian Удаляет заголовок из ответов сервера
|
||||
//! \~english Removes a previously added common reply header.
|
||||
//! \~russian Удаляет ранее добавленный общий заголовок ответа.
|
||||
void removeReplyHeader(const PIString & name) { reply_headers.remove(name); }
|
||||
|
||||
//! \~english Clears all custom response headers
|
||||
//! \~russian Очищает все пользовательские заголовки ответов
|
||||
//! \~english Clears all custom headers added to router replies.
|
||||
//! \~russian Очищает все пользовательские заголовки, добавленные к ответам маршрутизатора.
|
||||
void clearReplyHeaders() { reply_headers.clear(); }
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*! \file pihttpservermodule.h
|
||||
* \ingroup HTTP
|
||||
* \~\brief
|
||||
* \~english Module include for the public HTTP server API
|
||||
* \~russian Модульный include для публичного API HTTP-сервера
|
||||
*
|
||||
* \~\details
|
||||
* \~english Includes the primary public HTTP server class declarations.
|
||||
* \~russian Подключает основные публичные объявления классов HTTP-сервера.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -16,39 +26,21 @@
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
//! \defgroup HTTPServer HTTPServer
|
||||
//! \~\brief
|
||||
//! \~english HTTP server
|
||||
//! \~russian HTTP сервер
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english \section cmake_module_HTTPServer Building with CMake
|
||||
//! \~russian \section cmake_module_HTTPServer Сборка с использованием CMake
|
||||
//!
|
||||
//! \~\code
|
||||
//! find_package(PIP REQUIRED)
|
||||
//! target_link_libraries([target] PIP::HTTPServer)
|
||||
//! \endcode
|
||||
//!
|
||||
//! \~english \par Common
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides HTTP server based on libmicrohttpd
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают HTTP сервер, основанный на libmicrohttpd
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
//! Ivan Pelipenko peri4ko@yandex.ru;
|
||||
//! \~russian
|
||||
//! Иван Пелипенко peri4ko@yandex.ru;
|
||||
//!
|
||||
|
||||
#ifndef pihttpservermodule_H
|
||||
#define pihttpservermodule_H
|
||||
|
||||
//! \~\addtogroup HTTPServer
|
||||
//! \~\{
|
||||
//! \~\file pihttpservermodule.h
|
||||
//! \~\brief HTTP server module includes
|
||||
//! \~english HTTP server module includes
|
||||
//! \~russian Модуль включений HTTP сервера
|
||||
//! \~\details
|
||||
//! \~english This file provides includes for the HTTP server module
|
||||
//! \~russian Этот файл предоставляет включения для модуля HTTP сервера
|
||||
//! \~\}
|
||||
|
||||
#include "pihttpserver.h"
|
||||
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user