drogon
C++14/17-based HTTP application framework
Loading...
Searching...
No Matches
drogon::HttpAppFramework Class Referenceabstract
Inheritance diagram for drogon::HttpAppFramework:
Collaboration diagram for drogon::HttpAppFramework:

Public Member Functions

virtual void run ()=0
 Run the event loop.
virtual bool isRunning ()=0
 Return true if the framework is running.
virtual void quit ()=0
 Quit the event loop.
virtual trantor::EventLoop * getLoop () const =0
 Get the main event loop of the framework;.
virtual trantor::EventLoop * getIOLoop (size_t id) const =0
 Get an IO loop with id. E.g. 0 <= id < #Total thread-loops.
virtual HttpAppFrameworksetCustom404Page (const HttpResponsePtr &resp, bool set404=true)=0
 Set custom 404 page.
virtual HttpAppFrameworksetCustomErrorHandler (std::function< HttpResponsePtr(HttpStatusCode, const HttpRequestPtr &req)> &&resp_generator)=0
 Set custom error handler.
HttpAppFrameworksetCustomErrorHandler (std::function< HttpResponsePtr(HttpStatusCode)> &&resp_generator)
virtual const std::function< HttpResponsePtr(HttpStatusCode, const HttpRequestPtr &req)> & getCustomErrorHandler () const =0
 Get custom error handler.
template<typename T>
T * getPlugin ()
 Get the plugin object registered in the framework.
template<typename T>
std::shared_ptr< T > getSharedPlugin ()
 Get the shared_ptr plugin object registered in the framework.
virtual PluginBasegetPlugin (const std::string &name)=0
 the plugin object registered in the framework
virtual std::shared_ptr< PluginBasegetSharedPlugin (const std::string &name)=0
 Get the shared_ptr plugin object registered in the framework.
virtual HttpAppFrameworkregisterBeginningAdvice (const std::function< void()> &advice)=0
 Register a beginning advice.
virtual HttpAppFrameworkregisterNewConnectionAdvice (const std::function< bool(const trantor::InetAddress &, const trantor::InetAddress &)> &advice)=0
 Register an advice for new connections.
virtual HttpAppFrameworkregisterHttpResponseCreationAdvice (const std::function< void(const HttpResponsePtr &)> &advice)=0
 Register an advice for new HTTP responses.
virtual HttpAppFrameworkregisterSyncAdvice (const std::function< HttpResponsePtr(const HttpRequestPtr &)> &advice)=0
 Register a synchronous advice.
virtual HttpAppFrameworkregisterPreRoutingAdvice (const std::function< void(const HttpRequestPtr &, AdviceCallback &&, AdviceChainCallback &&)> &advice)=0
 Register an advice called before routing.
virtual HttpAppFrameworkregisterPreRoutingAdvice (const std::function< void(const HttpRequestPtr &)> &advice)=0
 Register an observer called before routing.
virtual HttpAppFrameworkregisterPostRoutingAdvice (const std::function< void(const HttpRequestPtr &, AdviceCallback &&, AdviceChainCallback &&)> &advice)=0
 Register an advice called after routing.
virtual HttpAppFrameworkregisterPostRoutingAdvice (const std::function< void(const HttpRequestPtr &)> &advice)=0
 Register an observer called after routing.
virtual HttpAppFrameworkregisterPreHandlingAdvice (const std::function< void(const HttpRequestPtr &, AdviceCallback &&, AdviceChainCallback &&)> &advice)=0
 Register an advice called before the request is handled.
virtual HttpAppFrameworkregisterPreHandlingAdvice (const std::function< void(const HttpRequestPtr &)> &advice)=0
 Register an observer called before the request is handled.
virtual HttpAppFrameworkregisterPostHandlingAdvice (const std::function< void(const HttpRequestPtr &, const HttpResponsePtr &)> &advice)=0
 Register an advice called after the request is handled.
virtual HttpAppFrameworkregisterPreSendingAdvice (const std::function< void(const HttpRequestPtr &, const HttpResponsePtr &)> &advice)=0
 Register an advice called before a response is sent to the client.
virtual HttpAppFrameworksetupFileLogger ()=0
 Setup output of logs to files.
virtual HttpAppFrameworkloadConfigFile (const std::string &fileName) noexcept(false)=0
 Load the configuration file with json format.
virtual HttpAppFrameworkloadConfigJson (const Json::Value &data) noexcept(false)=0
 Load the configuration from a Json::Value Object.
virtual HttpAppFrameworkloadConfigJson (Json::Value &&data) noexcept(false)=0
 Load the configuration from a Json::Value Object.
virtual HttpAppFrameworkregisterHttpSimpleController (const std::string &pathName, const std::string &ctrlName, const std::vector< internal::HttpConstraint > &constraints={})=0
 Register a HttpSimpleController object into the framework.
template<typename FUNCTION>
HttpAppFrameworkregisterHandler (const std::string &pathPattern, FUNCTION &&function, const std::vector< internal::HttpConstraint > &constraints={}, const std::string &handlerName="")
 Register a handler into the framework.
template<typename FUNCTION>
HttpAppFrameworkregisterHandlerViaRegex (const std::string &regExp, FUNCTION &&function, const std::vector< internal::HttpConstraint > &constraints={}, const std::string &handlerName="")
 Register a handler into the framework via a regular expression.
virtual HttpAppFrameworkregisterWebSocketController (const std::string &pathName, const std::string &ctrlName, const std::vector< internal::HttpConstraint > &constraints={})=0
 Register a WebSocketController into the framework.
virtual HttpAppFrameworkregisterWebSocketControllerRegex (const std::string &regExp, const std::string &ctrlName, const std::vector< internal::HttpConstraint > &constraints=std::vector< internal::HttpConstraint >{})=0
 Register a WebSocketController into the framework.
template<typename T>
HttpAppFrameworkregisterController (const std::shared_ptr< T > &ctrlPtr)
 Register controller objects created and initialized by the user.
template<typename T>
HttpAppFrameworkregisterFilter (const std::shared_ptr< T > &filterPtr)
 Register filter objects created and initialized by the user.
template<typename T>
HttpAppFrameworkregisterMiddleware (const std::shared_ptr< T > &middlewarePtr)
 Register middleware objects created and initialized by the user.
virtual HttpAppFrameworksetDefaultHandler (DefaultHandler handler)=0
virtual void forward (const HttpRequestPtr &req, std::function< void(const HttpResponsePtr &)> &&callback, const std::string &hostString="", double timeout=0)=0
 Forward the http request.
virtual std::vector< HttpHandlerInfo > getHandlersInfo () const =0
 Get information about the handlers registered to drogon.
virtual const Json::Value & getCustomConfig () const =0
 Get the custom configuration defined by users in the configuration file.
virtual HttpAppFrameworksetThreadNum (size_t threadNum)=0
 Set the number of threads for IO event loops.
virtual size_t getThreadNum () const =0
 Get the number of threads for IO event loops.
virtual HttpAppFrameworksetSSLFiles (const std::string &certPath, const std::string &keyPath)=0
virtual HttpAppFrameworksetSSLConfigCommands (const std::vector< std::pair< std::string, std::string > > &sslConfCmds)=0
virtual HttpAppFrameworkreloadSSLFiles ()=0
virtual void addPlugins (const Json::Value &configs)=0
 Add plugins.
virtual void addPlugin (const std::string &name, const std::vector< std::string > &dependencies, const Json::Value &config)=0
 Add a plugin.
virtual HttpAppFrameworkaddListener (const std::string &ip, uint16_t port, bool useSSL=false, const std::string &certFile="", const std::string &keyFile="", bool useOldTLS=false, const std::vector< std::pair< std::string, std::string > > &sslConfCmds={})=0
 Add a listener for http or https service.
virtual HttpAppFrameworkenableSession (const size_t timeout=0, Cookie::SameSite sameSite=Cookie::SameSite::kNull, const std::string &cookieKey="JSESSIONID", int maxAge=-1, std::function< std::string()> idGeneratorCallback=nullptr)=0
 Enable sessions supporting.
HttpAppFrameworkenableSession (const std::chrono::duration< double > &timeout, Cookie::SameSite sameSite=Cookie::SameSite::kNull, const std::string &cookieKey="JSESSIONID", int maxAge=-1, std::function< std::string()> idGeneratorCallback=nullptr)
 A wrapper of the above method.
virtual HttpAppFrameworkregisterSessionStartAdvice (const AdviceStartSessionCallback &advice)=0
 Register an advice called when starting a new session.
virtual HttpAppFrameworkregisterSessionDestroyAdvice (const AdviceDestroySessionCallback &advice)=0
 Register an advice called when destroying a session.
virtual HttpAppFrameworkdisableSession ()=0
 Disable sessions supporting.
virtual HttpAppFrameworksetDocumentRoot (const std::string &rootPath)=0
 Set the root path of HTTP document, default path is ./.
virtual const std::string & getDocumentRoot () const =0
 Get the document root directory.
virtual HttpAppFrameworksetStaticFileHeaders (const std::vector< std::pair< std::string, std::string > > &headers)=0
 Set the Static File Headers.
virtual HttpAppFrameworkaddALocation (const std::string &uriPrefix, const std::string &defaultContentType="", const std::string &alias="", bool isCaseSensitive=false, bool allowAll=true, bool isRecursive=true, const std::vector< std::string > &middlewareNames={})=0
 Add a location of static files for GET requests.
virtual HttpAppFrameworksetUploadPath (const std::string &uploadPath)=0
 Set the path to store uploaded files.
virtual const std::string & getUploadPath () const =0
 Get the path to store uploaded files.
virtual HttpAppFrameworksetFileTypes (const std::vector< std::string > &types)=0
 Set types of files that can be downloaded.
virtual HttpAppFrameworkenableDynamicViewsLoading (const std::vector< std::string > &libPaths, const std::string &outputPath="")=0
 Enable supporting for dynamic views loading.
virtual HttpAppFrameworksetMaxConnectionNum (size_t maxConnections)=0
 Set the maximum number of all connections.
virtual HttpAppFrameworksetMaxConnectionNumPerIP (size_t maxConnectionsPerIP)=0
 Set the maximum number of connections per remote IP.
virtual HttpAppFrameworkenableRunAsDaemon ()=0
 Make the application run as a daemon.
virtual HttpAppFrameworkdisableSigtermHandling ()=0
 Disable the handling of SIGTERM signal.
virtual HttpAppFrameworkenableRelaunchOnError ()=0
 Make the application restart after crashing.
virtual HttpAppFrameworksetLogPath (const std::string &logPath, const std::string &logfileBaseName="", size_t logSize=100000000, size_t maxFiles=0, bool useSpdlog=false)=0
 Set the output path of logs.
virtual HttpAppFrameworksetLogLevel (trantor::Logger::LogLevel level)=0
 Set the log level.
virtual HttpAppFrameworksetLogLocalTime (bool on)=0
 Set the log time display.
virtual HttpAppFrameworkenableSendfile (bool sendFile)=0
 Enable the sendfile system call in linux.
virtual HttpAppFrameworkenableGzip (bool useGzip)=0
 Enable gzip compression.
virtual bool isGzipEnabled () const =0
 Return true if gzip is enabled.
virtual HttpAppFrameworkenableBrotli (bool useBrotli)=0
 Enable brotli compression.
virtual bool isBrotliEnabled () const =0
 Return true if brotli is enabled.
virtual HttpAppFrameworksetStaticFilesCacheTime (int cacheTime)=0
 Set the time in which the static file response is cached in memory.
virtual int staticFilesCacheTime () const =0
 Get the time set by the above method.
virtual HttpAppFrameworksetIdleConnectionTimeout (size_t timeout)=0
 Set the lifetime of the connection without read or write.
HttpAppFrameworksetIdleConnectionTimeout (const std::chrono::duration< double > &timeout)
 A wrapper of the above method.
virtual HttpAppFrameworksetServerHeaderField (const std::string &server)=0
 Set the 'server' header field in each response sent by drogon.
virtual HttpAppFrameworkenableServerHeader (bool flag)=0
 Control if the 'Server' header is added to each HTTP response.
virtual HttpAppFrameworkenableDateHeader (bool flag)=0
 Control if the 'Date' header is added to each HTTP response.
virtual HttpAppFrameworksetKeepaliveRequestsNumber (const size_t number)=0
virtual HttpAppFrameworksetPipeliningRequestsNumber (const size_t number)=0
virtual HttpAppFrameworksetGzipStatic (bool useGzipStatic)=0
 Set the gzip_static option.
virtual HttpAppFrameworksetBrStatic (bool useGzipStatic)=0
 Set the br_static option.
virtual HttpAppFrameworksetClientMaxBodySize (size_t maxSize)=0
 Set the max body size of the requests received by drogon.
virtual HttpAppFrameworksetClientMaxMemoryBodySize (size_t maxSize)=0
 Set the maximum body size in memory of HTTP requests received by drogon.
virtual HttpAppFrameworksetClientMaxWebSocketMessageSize (size_t maxSize)=0
 Set the max size of messages sent by WebSocket client.
virtual HttpAppFrameworksetHomePage (const std::string &homePageFile)=0
virtual HttpAppFrameworksetTermSignalHandler (const std::function< void()> &handler)=0
 Set the TERM Signal Handler. This method provides a way to users for exiting program gracefully. When the TERM signal is received after app().run() is called, the handler is invoked. Drogon uses a default signal handler for the TERM signal, which calls the 'app().quit()' method when the TERM signal is received.
virtual HttpAppFrameworksetIntSignalHandler (const std::function< void()> &handler)=0
 Set the INT Signal Handler. This method provides a way to users for exiting program gracefully. When the INT signal is received after app().run() is called, the handler is invoked. Drogon uses a default signal handler for the INT signal, which calls the 'app().quit()' method when the INT signal is received.
virtual const std::string & getHomePage () const =0
 Get homepage, default is "index.html".
virtual HttpAppFrameworksetImplicitPageEnable (bool useImplicitPage)=0
 Set to enable implicit pages, enabled by default.
virtual bool isImplicitPageEnabled () const =0
 Return true if implicit pages are enabled.
virtual HttpAppFrameworksetImplicitPage (const std::string &implicitPageFile)=0
 Set the page which would the server load in if it detects that the user requested a directory.
virtual const std::string & getImplicitPage () const =0
 Get the implicit HTML page.
virtual orm::DbClientPtr getDbClient (const std::string &name="default")=0
 Get a database client by name.
virtual orm::DbClientPtr getFastDbClient (const std::string &name="default")=0
 Get a 'fast' database client by name.
virtual bool areAllDbClientsAvailable () const noexcept=0
 Check if all database clients in the framework are available (connect to the database successfully).
virtual nosql::RedisClientPtr getRedisClient (const std::string &name="default")=0
 Get a redis client by name.
virtual nosql::RedisClientPtr getFastRedisClient (const std::string &name="default")=0
 Get a 'fast' redis client by name.
virtual HttpAppFrameworksetJsonParserStackLimit (size_t limit) noexcept=0
 Set the maximum stack depth of the json parser when reading a json string, the default value is 1000.
virtual size_t getJsonParserStackLimit () const noexcept=0
 Get the maximum stack depth of the json parser when reading a json string.
virtual HttpAppFrameworksetUnicodeEscapingInJson (bool enable) noexcept=0
 This method is to enable or disable the unicode escaping (\u) in the json string of HTTP responses or requests. it works (disable successfully) when the version of JsonCpp >= 1.9.3, the unicode escaping is enabled by default.
virtual bool isUnicodeEscapingUsedInJson () const noexcept=0
 Check if the unicode escaping is used in the json string of HTTP requests and responses.
virtual HttpAppFrameworksetFloatPrecisionInJson (unsigned int precision, const std::string &precisionType="significant") noexcept=0
 Set the float precision in Json string of HTTP requests or responses with json content.
virtual const std::pair< unsigned int, std::string > & getFloatPrecisionInJson () const noexcept=0
 Get the float precision set by the above method.
virtual HttpAppFrameworkcreateDbClient (const std::string &dbType, const std::string &host, unsigned short port, const std::string &databaseName, const std::string &userName, const std::string &password, size_t connectionNum=1, const std::string &filename="", const std::string &name="default", bool isFast=false, const std::string &characterSet="", double timeout=-1.0, bool autoBatch=false)=0
 Create a database client.
virtual HttpAppFrameworkaddDbClient (const orm::DbConfig &config)=0
virtual HttpAppFrameworkcreateRedisClient (const std::string &ip, unsigned short port, const std::string &name="default", const std::string &password="", size_t connectionNum=1, bool isFast=false, double timeout=-1.0, unsigned int db=0, const std::string &username="")=0
 Create a redis client.
virtual const std::shared_ptr< trantor::Resolver > & getResolver () const =0
 Get the DNS resolver.
virtual bool supportSSL () const =0
 Return true is drogon supports SSL(https).
virtual size_t getCurrentThreadIndex () const =0
 Get the Current Thread Index whose range is [0, the total number of IO threads].
virtual std::vector< trantor::InetAddress > getListeners () const =0
 Get the addresses of listeners.
virtual void enableReusePort (bool enable=true)=0
 Enable ReusePort mode or not. If the mode is enabled, one can run multiple processes listening to the same port at the same time. If this method is not called, the feature is disabled.
virtual bool reusePort () const =0
 Return if the ReusePort mode is enabled.
virtual HttpAppFrameworksetExceptionHandler (ExceptionHandler handler)=0
 handler will be called upon an exception escapes a request handler
virtual const ExceptionHandler & getExceptionHandler () const =0
 returns the excaption handler
virtual HttpAppFrameworkregisterCustomExtensionMime (const std::string &ext, const std::string &mime)=0
 Adds a new custom extension to MIME type mapping.
virtual HttpAppFrameworkenableCompressedRequest (bool enable=true)=0
virtual bool isCompressedRequestEnabled () const =0
virtual int64_t getConnectionCount () const =0
virtual HttpAppFrameworksetBeforeListenSockOptCallback (std::function< void(int)> cb)=0
 Set the before listen setsockopt callback.
virtual HttpAppFrameworksetAfterAcceptSockOptCallback (std::function< void(int)> cb)=0
 Set the after accept setsockopt callback.
virtual HttpAppFrameworksetConnectionCallback (std::function< void(const trantor::TcpConnectionPtr &)> cb)=0
 Set the client disconnect or connect callback.
virtual HttpAppFrameworkenableRequestStream (bool enable=true)=0
virtual bool isRequestStreamEnabled () const =0

Static Public Member Functions

static HttpAppFrameworkinstance ()
 Get the instance of HttpAppFramework.

Member Function Documentation

◆ addALocation()

virtual HttpAppFramework & drogon::HttpAppFramework::addALocation ( const std::string & uriPrefix,
const std::string & defaultContentType = "",
const std::string & alias = "",
bool isCaseSensitive = false,
bool allowAll = true,
bool isRecursive = true,
const std::vector< std::string > & middlewareNames = {} )
pure virtual

Add a location of static files for GET requests.

Parameters
uriPrefixThe URI prefix of the location prefixed with "/"
defaultContentTypeThe default content type of the static files without an extension.
aliasThe location in file system, if it is prefixed with "/", it presents an absolute path, otherwise it presents a relative path to the document_root path.
isCaseSensitive
allowAllIf it is set to false, only static files with a valid extension can be accessed.
isRecursiveIf it is set to false, files in sub directories can't be accessed.
middlewareNamesThe list of middlewares which acting on the location.
Returns
HttpAppFramework&

◆ addListener()

virtual HttpAppFramework & drogon::HttpAppFramework::addListener ( const std::string & ip,
uint16_t port,
bool useSSL = false,
const std::string & certFile = "",
const std::string & keyFile = "",
bool useOldTLS = false,
const std::vector< std::pair< std::string, std::string > > & sslConfCmds = {} )
pure virtual

Add a listener for http or https service.

Parameters
ipis the ip that the listener listens on.
portis the port that the listener listens on.
useSSLif the parameter is true, the listener is used for the https service.
certFile
keyFilespecify the cert file and the private key file for this listener. If they are empty, the global configuration set by the above method is used.
useOldTLSif true, the TLS1.0/1.1 are enabled for HTTPS connections.
sslConfCmdsvector of ssl configuration key/value pairs.
Note
This operation can be performed by an option in the configuration file.

◆ addPlugin()

virtual void drogon::HttpAppFramework::addPlugin ( const std::string & name,
const std::vector< std::string > & dependencies,
const Json::Value & config )
pure virtual

Add a plugin.

Parameters
nameName of the plugin
dependenciesNames of plugins this plugin depends on
configCustom config for the plugin

◆ addPlugins()

virtual void drogon::HttpAppFramework::addPlugins ( const Json::Value & configs)
pure virtual

Add plugins.

Parameters
configsThe plugins array
Note
This operation can be performed by an option in the configuration file.

◆ createDbClient()

virtual HttpAppFramework & drogon::HttpAppFramework::createDbClient ( const std::string & dbType,
const std::string & host,
unsigned short port,
const std::string & databaseName,
const std::string & userName,
const std::string & password,
size_t connectionNum = 1,
const std::string & filename = "",
const std::string & name = "default",
bool isFast = false,
const std::string & characterSet = "",
double timeout = -1.0,
bool autoBatch = false )
pure virtual

Create a database client.

Parameters
dbTypeThe database type is one of "postgresql","mysql","sqlite3".
hostIP or host name.
portThe port on which the database server is listening.
databaseNameDatabase name
userNameUser name
passwordPassword for the database server
connectionNumThe number of connections to the database server. It's valid only if isFast is false.
filenameThe file name of sqlite3 database file.
nameThe client name.
isFastIndicates if the client is a fast database client.
characterSetThe character set of the database server.
timeoutThe timeout in seconds for executing SQL queries. zero or negative value means no timeout.
Note
This operation can be performed by an option in the configuration file.

◆ createRedisClient()

virtual HttpAppFramework & drogon::HttpAppFramework::createRedisClient ( const std::string & ip,
unsigned short port,
const std::string & name = "default",
const std::string & password = "",
size_t connectionNum = 1,
bool isFast = false,
double timeout = -1.0,
unsigned int db = 0,
const std::string & username = "" )
pure virtual

Create a redis client.

Parameters
ipIP of redis server.
portThe port on which the redis server is listening.
nameThe client name.
usernameUsername for redis server
passwordPassword for the redis server
connectionNumThe number of connections to the redis server.
isFastIndicates if the client is a fast database client.
Note
This operation can be performed by an option in the configuration file.

◆ disableSession()

virtual HttpAppFramework & drogon::HttpAppFramework::disableSession ( )
pure virtual

Disable sessions supporting.

Note
This operation can be performed by an option in the configuration file.

◆ disableSigtermHandling()

virtual HttpAppFramework & drogon::HttpAppFramework::disableSigtermHandling ( )
pure virtual

Disable the handling of SIGTERM signal.

Enabled by default.

Note
This operation can be performed by an option in the configuration file. When disabled setTermSignalHandler() is useless

◆ enableBrotli()

virtual HttpAppFramework & drogon::HttpAppFramework::enableBrotli ( bool useBrotli)
pure virtual

Enable brotli compression.

Parameters
useBrotliif the parameter is true, use brotli to compress the response body's content; The default value is true.
Note
This operation can be performed by an option in the configuration file. After brotli is enabled, brotli is used under the following conditions:
  1. The content type of response is not a binary type.
  2. The content length is bigger than 1024 bytes.

◆ enableDateHeader()

virtual HttpAppFramework & drogon::HttpAppFramework::enableDateHeader ( bool flag)
pure virtual

Control if the 'Date' header is added to each HTTP response.

Note
These operations can be performed by options in the configuration file. The headers are sent to clients by default.

◆ enableDynamicViewsLoading()

virtual HttpAppFramework & drogon::HttpAppFramework::enableDynamicViewsLoading ( const std::vector< std::string > & libPaths,
const std::string & outputPath = "" )
pure virtual

Enable supporting for dynamic views loading.

Parameters
libPathsis a vector that contains paths to view files.
outputPathis the directory where the output source files locate. If it is set to an empty string, drogon use libPaths as output paths. If the path isn't prefixed with /, it is the relative path of the current working directory.
Note
It is disabled by default. This operation can be performed by an option in the configuration file.

◆ enableGzip()

virtual HttpAppFramework & drogon::HttpAppFramework::enableGzip ( bool useGzip)
pure virtual

Enable gzip compression.

Parameters
useGzipif the parameter is true, use gzip to compress the response body's content; The default value is true.
Note
This operation can be performed by an option in the configuration file. After gzip is enabled, gzip is used under the following conditions:
  1. The content type of response is not a binary type.
  2. The content length is bigger than 1024 bytes.

◆ enableRelaunchOnError()

virtual HttpAppFramework & drogon::HttpAppFramework::enableRelaunchOnError ( )
pure virtual

Make the application restart after crashing.

Disabled by default.

Note
This operation can be performed by an option in the configuration file.

◆ enableReusePort()

virtual void drogon::HttpAppFramework::enableReusePort ( bool enable = true)
pure virtual

Enable ReusePort mode or not. If the mode is enabled, one can run multiple processes listening to the same port at the same time. If this method is not called, the feature is disabled.

Note
This operation can be performed by an option in the configuration file.

◆ enableRunAsDaemon()

virtual HttpAppFramework & drogon::HttpAppFramework::enableRunAsDaemon ( )
pure virtual

Make the application run as a daemon.

Disabled by default.

Note
This operation can be performed by an option in the configuration file.

◆ enableSendfile()

virtual HttpAppFramework & drogon::HttpAppFramework::enableSendfile ( bool sendFile)
pure virtual

Enable the sendfile system call in linux.

Parameters
sendFileif the parameter is true, sendfile() system-call is used to send static files to clients; The default value is true.
Note
This operation can be performed by an option in the configuration file. Even though sendfile() is enabled, only files larger than 200k are sent this way, because the advantages of sendfile() can only be reflected in sending large files.

◆ enableServerHeader()

virtual HttpAppFramework & drogon::HttpAppFramework::enableServerHeader ( bool flag)
pure virtual

Control if the 'Server' header is added to each HTTP response.

Note
These operations can be performed by options in the configuration file. The headers are sent to clients by default.

◆ enableSession() [1/2]

virtual HttpAppFramework & drogon::HttpAppFramework::enableSession ( const size_t timeout = 0,
Cookie::SameSite sameSite = Cookie::SameSite::kNull,
const std::string & cookieKey = "JSESSIONID",
int maxAge = -1,
std::function< std::string()> idGeneratorCallback = nullptr )
pure virtual

Enable sessions supporting.

Parameters
timeoutThe number of seconds which is the timeout of a session
sameSiteThe default value of SameSite attribute
cookieKeyThe key of the session cookie
Note
Session support is disabled by default. If there isn't any request from a client for timeout(>0) seconds, the session of the client is destroyed. If the timeout parameter is equal to 0, sessions will remain permanently This operation can be performed by an option in the configuration file.

◆ enableSession() [2/2]

HttpAppFramework & drogon::HttpAppFramework::enableSession ( const std::chrono::duration< double > & timeout,
Cookie::SameSite sameSite = Cookie::SameSite::kNull,
const std::string & cookieKey = "JSESSIONID",
int maxAge = -1,
std::function< std::string()> idGeneratorCallback = nullptr )
inline

A wrapper of the above method.

Example: Users can set the timeout value as follows:

app().enableSession(12min);
virtual HttpAppFramework & enableSession(const size_t timeout=0, Cookie::SameSite sameSite=Cookie::SameSite::kNull, const std::string &cookieKey="JSESSIONID", int maxAge=-1, std::function< std::string()> idGeneratorCallback=nullptr)=0
Enable sessions supporting.
HttpAppFramework & app()
A wrapper of the instance() method.
Definition HttpAppFramework.h:1656

◆ forward()

virtual void drogon::HttpAppFramework::forward ( const HttpRequestPtr & req,
std::function< void(const HttpResponsePtr &)> && callback,
const std::string & hostString = "",
double timeout = 0 )
pure virtual

Forward the http request.

Parameters
reqthe HTTP request to be forwarded;
hostStringis the address where the request is forwarded. The following strings are valid for the parameter:
https://www.baidu.com
http://www.baidu.com
https://127.0.0.1:8080/
http://127.0.0.1
http://[::1]:8080/
Parameters
timeoutSee the timeout parameter of the sendRequest method of the HttpClient class. this parameter is only valid when the hostString is not empty.
callbackis called when the response is created.
Note
If the hostString parameter is empty, the request is handled by the same application, so in this condition one should modify the path of the req parameter before forwarding to avoid infinite loop processing.

This method can be used to implement reverse proxy or redirection on the server side.

◆ getCurrentThreadIndex()

virtual size_t drogon::HttpAppFramework::getCurrentThreadIndex ( ) const
pure virtual

Get the Current Thread Index whose range is [0, the total number of IO threads].

Returns
size_t If the current thread is the main EventLoop thread (in which the app().run() is called), the number of the IO threads is returned. If the current thread is a network IO thread, the index of it in the range [0, the number of IO threads) is returned. otherwise the maximum value of type size_t is returned.
Note
Basically this method is used for storing thread-related various in an array and users can use indexes returned by this method to access them. This is much faster than using a map. If the array is properly initialized at the beginning, users can access it without locks.

◆ getCustomErrorHandler()

virtual const std::function< HttpResponsePtr(HttpStatusCode, const HttpRequestPtr &req)> & drogon::HttpAppFramework::getCustomErrorHandler ( ) const
pure virtual

Get custom error handler.

Returns
A const-reference to the error handler set using setCustomErrorHandler. If none was provided, the default error handler is returned.

◆ getDbClient()

virtual orm::DbClientPtr drogon::HttpAppFramework::getDbClient ( const std::string & name = "default")
pure virtual

Get a database client by name.

Note
This method must be called after the framework has been run.

◆ getFastDbClient()

virtual orm::DbClientPtr drogon::HttpAppFramework::getFastDbClient ( const std::string & name = "default")
pure virtual

Get a 'fast' database client by name.

Note
This method must be called after the framework has been run.

◆ getFastRedisClient()

virtual nosql::RedisClientPtr drogon::HttpAppFramework::getFastRedisClient ( const std::string & name = "default")
pure virtual

Get a 'fast' redis client by name.

Note
This method must be called after the framework has been run.

◆ getFloatPrecisionInJson()

virtual const std::pair< unsigned int, std::string > & drogon::HttpAppFramework::getFloatPrecisionInJson ( ) const
pure virtualnoexcept

Get the float precision set by the above method.

Returns
std::pair<size_t, std::string>

◆ getHandlersInfo()

virtual std::vector< HttpHandlerInfo > drogon::HttpAppFramework::getHandlersInfo ( ) const
pure virtual

Get information about the handlers registered to drogon.

Returns
The first item of std::tuple in the return value represents the path pattern of the handler; The last item in std::tuple is the description of the handler.

◆ getHomePage()

virtual const std::string & drogon::HttpAppFramework::getHomePage ( ) const
pure virtual

Get homepage, default is "index.html".

Note
This method must be called after the framework has been run.

◆ getImplicitPage()

virtual const std::string & drogon::HttpAppFramework::getImplicitPage ( ) const
pure virtual

Get the implicit HTML page.

Note
This method must be called after the framework has been run.

◆ getIOLoop()

virtual trantor::EventLoop * drogon::HttpAppFramework::getIOLoop ( size_t id) const
pure virtual

Get an IO loop with id. E.g. 0 <= id < #Total thread-loops.

Note
The event loop is one of the network IO loops. Use the loop for events/actions rather then the main thread. REMARKS : Function assumed the number of threads will not exceed 2^32. Change to long long for alien computers.

◆ getListeners()

virtual std::vector< trantor::InetAddress > drogon::HttpAppFramework::getListeners ( ) const
pure virtual

Get the addresses of listeners.

Returns
std::vector<trantor::InetAddress>
Note
This method should be called after calling the app().run(). One could run this method in an AOP join point (such as the BeginningAdvice).

◆ getLoop()

virtual trantor::EventLoop * drogon::HttpAppFramework::getLoop ( ) const
pure virtual

Get the main event loop of the framework;.

Note
The event loop is not the network IO loop, but the main event loop of the framework in which only some timer tasks are running; User can run some timer tasks or other tasks in this loop; This method can be call in any thread.

◆ getPlugin() [1/2]

template<typename T>
T * drogon::HttpAppFramework::getPlugin ( )
inline

Get the plugin object registered in the framework.

Note
This method is usually called after the framework runs. Calling this method in the initAndStart() method of plugins is also valid.

◆ getPlugin() [2/2]

virtual PluginBase * drogon::HttpAppFramework::getPlugin ( const std::string & name)
pure virtual

the plugin object registered in the framework

Parameters
nameis the class name of the plugin.
Note
This method is usually called after the framework runs. Calling this method in the initAndStart() method of plugins is also valid.

◆ getRedisClient()

virtual nosql::RedisClientPtr drogon::HttpAppFramework::getRedisClient ( const std::string & name = "default")
pure virtual

Get a redis client by name.

Note
This method must be called after the framework has been run.

◆ getResolver()

virtual const std::shared_ptr< trantor::Resolver > & drogon::HttpAppFramework::getResolver ( ) const
pure virtual

Get the DNS resolver.

Note
When the c-ares library is installed in the system, it runs with the best performance.

◆ getSharedPlugin() [1/2]

template<typename T>
std::shared_ptr< T > drogon::HttpAppFramework::getSharedPlugin ( )
inline

Get the shared_ptr plugin object registered in the framework.

Note
This method is usually called after the framework runs. Calling this method in the initAndStart() method of plugins is also valid.

◆ getSharedPlugin() [2/2]

virtual std::shared_ptr< PluginBase > drogon::HttpAppFramework::getSharedPlugin ( const std::string & name)
pure virtual

Get the shared_ptr plugin object registered in the framework.

Note
This method is usually called after the framework runs. Calling this method in the initAndStart() method of plugins is also valid.

◆ instance()

HttpAppFramework & drogon::HttpAppFramework::instance ( )
static

Get the instance of HttpAppFramework.

HttpAppFramework works at singleton mode, so any calling of this method gets the same instance; Calling drogon::HttpAppFramework::instance() can be replaced by a simple interface – drogon::app()

◆ isImplicitPageEnabled()

virtual bool drogon::HttpAppFramework::isImplicitPageEnabled ( ) const
pure virtual

Return true if implicit pages are enabled.

Note
This method must be called after the framework has been run.

◆ loadConfigFile()

virtual HttpAppFramework & drogon::HttpAppFramework::loadConfigFile ( const std::string & fileName)
pure virtual

Load the configuration file with json format.

Parameters
fileNamethe configuration file

◆ loadConfigJson() [1/2]

virtual HttpAppFramework & drogon::HttpAppFramework::loadConfigJson ( const Json::Value & data)
pure virtualnoexcept

Load the configuration from a Json::Value Object.

Parameters
dataJson::Value Object containing the configuration.
Note
Please refer to the configuration file for the content of the json object.

◆ loadConfigJson() [2/2]

virtual HttpAppFramework & drogon::HttpAppFramework::loadConfigJson ( Json::Value && data)
pure virtualnoexcept

Load the configuration from a Json::Value Object.

Parameters
datarvalue reference to a Json::Value object containing the configuration.
Note
Please refer to the configuration file for the content of the json object.

◆ quit()

virtual void drogon::HttpAppFramework::quit ( )
pure virtual

Quit the event loop.

Calling this method results in stopping all network IO in the framework and interrupting the blocking of the run() method. Usually, after calling this method, the application exits (when the run() method is called in the main thread).

Note
This method can be called in any thread and anywhere. This method should not be called before calling run().

◆ registerBeginningAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerBeginningAdvice ( const std::function< void()> & advice)
pure virtual

Register a beginning advice.

Parameters
adviceis called immediately after the main event loop runs.

◆ registerController()

template<typename T>
HttpAppFramework & drogon::HttpAppFramework::registerController ( const std::shared_ptr< T > & ctrlPtr)
inline

Register controller objects created and initialized by the user.

Drogon can only automatically create controllers using the default constructor. Sometimes users want to be able to create controllers using constructors with parameters. Controllers created by user in this way should be registered to the framework via this method. The macro or configuration file is still valid for the path routing configuration of the controller created by users.

Note
The declaration of the controller class must be as follows:
class ApiTest : public drogon::HttpController<ApiTest, false>
{
public:
ApiTest(const std::string &str);
...
};
The reflection base class template for HTTP controllers.
Definition HttpController.h:60
The second template parameter must be explicitly set to false to disable automatic creation. And then user can create and register it somewhere as follows:
auto ctrlPtr=std::make_shared<ApiTest>("hello world");
HttpAppFramework & registerController(const std::shared_ptr< T > &ctrlPtr)
Register controller objects created and initialized by the user.
Definition HttpAppFramework.h:672
This method should be called before calling the app().run() method.

◆ registerFilter()

template<typename T>
HttpAppFramework & drogon::HttpAppFramework::registerFilter ( const std::shared_ptr< T > & filterPtr)
inline

Register filter objects created and initialized by the user.

This method is similar to the above method.

◆ registerHandler()

template<typename FUNCTION>
HttpAppFramework & drogon::HttpAppFramework::registerHandler ( const std::string & pathPattern,
FUNCTION && function,
const std::vector< internal::HttpConstraint > & constraints = {},
const std::string & handlerName = "" )
inline

Register a handler into the framework.

Parameters
pathPatternWhen the path of a http request matches the pathPattern, the handler indicated by the function parameter is called.
functionindicates any type of callable object with a valid processing interface.
constraintsis the same as the third parameter in the above method.

Example:

app().registerHandler("/hello?username={1}",
[](const HttpRequestPtr& req,
std::function<void (const HttpResponsePtr&)>
&&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"});
HttpAppFramework & registerHandler(const std::string &pathPattern, FUNCTION &&function, const std::vector< internal::HttpConstraint > &constraints={}, const std::string &handlerName="")
Register a handler into the framework.
Definition HttpAppFramework.h:535
static HttpResponsePtr newHttpJsonResponse(const Json::Value &data)
Note
As you can see in the above example, this method supports parameters mapping.

◆ registerHandlerViaRegex()

template<typename FUNCTION>
HttpAppFramework & drogon::HttpAppFramework::registerHandlerViaRegex ( const std::string & regExp,
FUNCTION && function,
const std::vector< internal::HttpConstraint > & constraints = {},
const std::string & handlerName = "" )
inline

Register a handler into the framework via a regular expression.

Parameters
regExpA regular expression string, when the path of a http request matches the regular expression, the handler indicated by the function parameter is called.
Note
When the match is successful, Each string that matches a subexpression is sequentially mapped to a handler parameter.
Parameters
functionindicates any type of callable object with a valid processing interface.
constraintsis the same as the third parameter in the above method.
handlerNamea name for the handler.
Returns
HttpAppFramework&

◆ registerHttpResponseCreationAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerHttpResponseCreationAdvice ( const std::function< void(const HttpResponsePtr &)> & advice)
pure virtual

Register an advice for new HTTP responses.

Parameters
adviceis called immediately when a new HTTP response is created. Users can use the callback to modify the response if they want.
Note
This advice is called before any subsequent operation on the response is performed by drogon or applications, so some modification (e.g. modification on the status code) in this callback may be override by subsequent operations.
Returns
HttpAppFramework&

◆ registerHttpSimpleController()

virtual HttpAppFramework & drogon::HttpAppFramework::registerHttpSimpleController ( const std::string & pathName,
const std::string & ctrlName,
const std::vector< internal::HttpConstraint > & constraints = {} )
pure virtual

Register a HttpSimpleController object into the framework.

Parameters
pathNameWhen the path of a http request is equal to the pathName, the asyncHandleHttpRequest() method of the controller is called.
ctrlNameis the name of the controller. It includes the namespace to which the controller belongs.
constraintsis a vector containing Http methods or middleware names
Example:
app.registerHttpSimpleController("/userinfo","UserInfoCtrl",{Get,"LoginFilter"});
Note
Users can perform the same operation through the configuration file or a macro in the header file.

◆ registerMiddleware()

template<typename T>
HttpAppFramework & drogon::HttpAppFramework::registerMiddleware ( const std::shared_ptr< T > & middlewarePtr)
inline

Register middleware objects created and initialized by the user.

This method is similar to the above method.

◆ registerNewConnectionAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerNewConnectionAdvice ( const std::function< bool(const trantor::InetAddress &, const trantor::InetAddress &)> & advice)
pure virtual

Register an advice for new connections.

Parameters
adviceis called immediately when a new connection is established. the first parameter of it is the remote address of the new connection, the second one is the local address of it. If the advice returns a false value, drogon closes the connection. Users can use this advice to implement some security policies.

◆ registerPostHandlingAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerPostHandlingAdvice ( const std::function< void(const HttpRequestPtr &, const HttpResponsePtr &)> & advice)
pure virtual

Register an advice called after the request is handled.

Parameters
adviceis called immediately after the request is handled and a response object is created by handlers.

◆ registerPostRoutingAdvice() [1/2]

virtual HttpAppFramework & drogon::HttpAppFramework::registerPostRoutingAdvice ( const std::function< void(const HttpRequestPtr &)> & advice)
pure virtual

Register an observer called after routing.

Parameters
adviceis called at the same time as the above advice. It can be thought of as an observer who cannot respond to http requests.
Note
This advice has less overhead than the above one. If one does not intend to intercept the http request, please use this interface.

◆ registerPostRoutingAdvice() [2/2]

virtual HttpAppFramework & drogon::HttpAppFramework::registerPostRoutingAdvice ( const std::function< void(const HttpRequestPtr &, AdviceCallback &&, AdviceChainCallback &&)> & advice)
pure virtual

Register an advice called after routing.

Parameters
adviceis called immediately after the request matches a handler path and before any filters/middlewares applies. The parameters of the advice are same as those of the doFilter method of the Filter class.

◆ registerPreHandlingAdvice() [1/2]

virtual HttpAppFramework & drogon::HttpAppFramework::registerPreHandlingAdvice ( const std::function< void(const HttpRequestPtr &)> & advice)
pure virtual

Register an observer called before the request is handled.

Parameters
adviceis called at the same time as the above advice. It can be thought of as an observer who cannot respond to http requests. This advice has less overhead than the above one. If one does not intend to intercept the http request, please use this interface.

◆ registerPreHandlingAdvice() [2/2]

virtual HttpAppFramework & drogon::HttpAppFramework::registerPreHandlingAdvice ( const std::function< void(const HttpRequestPtr &, AdviceCallback &&, AdviceChainCallback &&)> & advice)
pure virtual

Register an advice called before the request is handled.

Parameters
adviceis called immediately after the request is approved by all filters/middlewares and before it is handled. The parameters of the advice are same as those of the doFilter method of the Filter class.

◆ registerPreRoutingAdvice() [1/2]

virtual HttpAppFramework & drogon::HttpAppFramework::registerPreRoutingAdvice ( const std::function< void(const HttpRequestPtr &)> & advice)
pure virtual

Register an observer called before routing.

Parameters
adviceis called at the same time as the above advice. It can be thought of as an observer who cannot respond to http requests.
Note
This advice has less overhead than the above one. If one does not intend to intercept the http request, please use this interface.

◆ registerPreRoutingAdvice() [2/2]

virtual HttpAppFramework & drogon::HttpAppFramework::registerPreRoutingAdvice ( const std::function< void(const HttpRequestPtr &, AdviceCallback &&, AdviceChainCallback &&)> & advice)
pure virtual

Register an advice called before routing.

Parameters
adviceis called after all the synchronous advice return nullptr and before the request is routed to any handler. The parameters of the advice are same as those of the doFilter method of the Filter class.

◆ registerPreSendingAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerPreSendingAdvice ( const std::function< void(const HttpRequestPtr &, const HttpResponsePtr &)> & advice)
pure virtual

Register an advice called before a response is sent to the client.

Note
This advice is different from the PostHandlingAdvice, responses to static resources are also handled here.

◆ registerSessionDestroyAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerSessionDestroyAdvice ( const AdviceDestroySessionCallback & advice)
pure virtual

Register an advice called when destroying a session.

Parameters
adviceis called with the session id.

◆ registerSessionStartAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerSessionStartAdvice ( const AdviceStartSessionCallback & advice)
pure virtual

Register an advice called when starting a new session.

Parameters
adviceis called with the session id.

◆ registerSyncAdvice()

virtual HttpAppFramework & drogon::HttpAppFramework::registerSyncAdvice ( const std::function< HttpResponsePtr(const HttpRequestPtr &)> & advice)
pure virtual

Register a synchronous advice.

Parameters
adviceis called immediately after the request is created. If a no-empty response is returned by the advice, it is sent to the client and no handler is invoked.
Note
The following diagram shows the location of the AOP join points during http request processing.
+-----------+ +----------+
| Request | | Response |
+-----------+ +----------+
| ^
v |
sync join point o----------->[HttpResponsePtr]----------->+
| |
v |
Pre-routing join point o----------->[Advice callback]----------->+
| |
v Invalid path |
[Find Handler]---------------->[404]----------->+
| |
v |
Post-routing join point o----------->[Advice callback]----------->+
| |
v Invalid method |
[Check Method]---------------->[405]----------->+
| |
v |
[Filters/Middlewares]------>[Filter callback]------>+
| |
v Y |
[Is OPTIONS method?]------------->[200]----------->+
| |
v |
Pre-handling join point o----------->[Advice callback]----------->+
| |
v |
[Handler] |
| |
v |
Post-handling join point o---------------------------------------->+
| |
v |
[Middlewares post logic]--->[Middleware callback]--->+

◆ registerWebSocketController()

virtual HttpAppFramework & drogon::HttpAppFramework::registerWebSocketController ( const std::string & pathName,
const std::string & ctrlName,
const std::vector< internal::HttpConstraint > & constraints = {} )
pure virtual

Register a WebSocketController into the framework.

The parameters of this method are the same as those in the registerHttpSimpleController() method.

◆ registerWebSocketControllerRegex()

virtual HttpAppFramework & drogon::HttpAppFramework::registerWebSocketControllerRegex ( const std::string & regExp,
const std::string & ctrlName,
const std::vector< internal::HttpConstraint > & constraints = std::vector< internal::HttpConstraint >{} )
pure virtual

Register a WebSocketController into the framework.

The parameters of this method are the same as those in the registerHttpSimpleController() method but using regular expression string for path.

◆ reloadSSLFiles()

virtual HttpAppFramework & drogon::HttpAppFramework::reloadSSLFiles ( )
pure virtual

Reload the global cert file and private key file for https server Note: The goal of this method is not to make the framework use the new SSL path, but rather to reload the new content from the old path while the framework is still running. Typically, when our SSL is about to expire, we need to reload the SSL. The purpose of this function is to use the new SSL certificate without stopping the framework.

◆ run()

virtual void drogon::HttpAppFramework::run ( )
pure virtual

Run the event loop.

Calling this method starts the IO event loops and the main loop of the application; This method can be called in the main thread or any other thread. This method blocks the current thread until the main event loop exits.

◆ setAfterAcceptSockOptCallback()

virtual HttpAppFramework & drogon::HttpAppFramework::setAfterAcceptSockOptCallback ( std::function< void(int)> cb)
pure virtual

Set the after accept setsockopt callback.

Parameters
cbThis callback will be called after accept

◆ setBeforeListenSockOptCallback()

virtual HttpAppFramework & drogon::HttpAppFramework::setBeforeListenSockOptCallback ( std::function< void(int)> cb)
pure virtual

Set the before listen setsockopt callback.

Parameters
cbThis callback will be called before the listen

◆ setBrStatic()

virtual HttpAppFramework & drogon::HttpAppFramework::setBrStatic ( bool useGzipStatic)
pure virtual

Set the br_static option.

If it is set to true, when the client requests a static file, drogon first finds the compressed file with the extension ".br" in the same path and send the compressed file to the client. The default value is true.

Note
This operation can be performed by an option in the configuration file.

◆ setClientMaxBodySize()

virtual HttpAppFramework & drogon::HttpAppFramework::setClientMaxBodySize ( size_t maxSize)
pure virtual

Set the max body size of the requests received by drogon.

The default value is 1M.

Note
This operation can be performed by an option in the configuration file.

◆ setClientMaxMemoryBodySize()

virtual HttpAppFramework & drogon::HttpAppFramework::setClientMaxMemoryBodySize ( size_t maxSize)
pure virtual

Set the maximum body size in memory of HTTP requests received by drogon.

The default value is "64K" bytes. If the body size of a HTTP request exceeds this limit, the body is stored to a temporary file for processing.

Note
This operation can be performed by an option in the configuration file.

◆ setClientMaxWebSocketMessageSize()

virtual HttpAppFramework & drogon::HttpAppFramework::setClientMaxWebSocketMessageSize ( size_t maxSize)
pure virtual

Set the max size of messages sent by WebSocket client.

The default value is 128K.

Note
This operation can be performed by an option in the configuration file.

◆ setConnectionCallback()

virtual HttpAppFramework & drogon::HttpAppFramework::setConnectionCallback ( std::function< void(const trantor::TcpConnectionPtr &)> cb)
pure virtual

Set the client disconnect or connect callback.

Parameters
cbThis callback will be called, when the client disconnect or connect

◆ setCustom404Page()

virtual HttpAppFramework & drogon::HttpAppFramework::setCustom404Page ( const HttpResponsePtr & resp,
bool set404 = true )
pure virtual

Set custom 404 page.

Parameters
respis the object set to 404 response After calling this method, the resp object is returned by the HttpResponse::newNotFoundResponse() method.
set404if true, the status code of the resp will be set to 404 automatically

◆ setCustomErrorHandler()

virtual HttpAppFramework & drogon::HttpAppFramework::setCustomErrorHandler ( std::function< HttpResponsePtr(HttpStatusCode, const HttpRequestPtr &req)> && resp_generator)
pure virtual

Set custom error handler.

Parameters
resp_generatoris invoked when an error in the framework needs to be sent to the client to provide a custom layout.

◆ setDefaultHandler()

virtual HttpAppFramework & drogon::HttpAppFramework::setDefaultHandler ( DefaultHandler handler)
pure virtual

Register a default handler into the framework when no handler matches the request. If set, it is executed if the static file router does not find any file corresponding to the request. Thus it replaces the default 404 not found response.

Parameters
handlerfunction indicates any type of callable object with a valid processing interface.

◆ setDocumentRoot()

virtual HttpAppFramework & drogon::HttpAppFramework::setDocumentRoot ( const std::string & rootPath)
pure virtual

Set the root path of HTTP document, default path is ./.

Note
This operation can be performed by an option in the configuration file.

◆ setFileTypes()

virtual HttpAppFramework & drogon::HttpAppFramework::setFileTypes ( const std::vector< std::string > & types)
pure virtual

Set types of files that can be downloaded.

Example:

app.setFileTypes({"html","txt","png","jpg"});
Note
This operation can be performed by an option in the configuration file.

◆ setFloatPrecisionInJson()

virtual HttpAppFramework & drogon::HttpAppFramework::setFloatPrecisionInJson ( unsigned int precision,
const std::string & precisionType = "significant" )
pure virtualnoexcept

Set the float precision in Json string of HTTP requests or responses with json content.

Parameters
precisionThe maximum digits length.
precisionTypeMust be "significant" or "decimal", defaults to "significant" that means setting max number of significant digits in string, "decimal" means setting max number of digits after "." in string
Returns
HttpAppFramework&

◆ setGzipStatic()

virtual HttpAppFramework & drogon::HttpAppFramework::setGzipStatic ( bool useGzipStatic)
pure virtual

Set the gzip_static option.

If it is set to true, when the client requests a static file, drogon first finds the compressed file with the extension ".gz" in the same path and send the compressed file to the client. The default value is true.

Note
This operation can be performed by an option in the configuration file.

◆ setHomePage()

virtual HttpAppFramework & drogon::HttpAppFramework::setHomePage ( const std::string & homePageFile)
pure virtual

If there isn't any handler registered to the path "/", the home page file in the "document_root" is send to clients as a response to the request for "/".

Note
This operation can be performed by an option in the configuration file.

◆ setIdleConnectionTimeout() [1/2]

HttpAppFramework & drogon::HttpAppFramework::setIdleConnectionTimeout ( const std::chrono::duration< double > & timeout)
inline

A wrapper of the above method.

Example: Users can set the timeout value as follows:

virtual HttpAppFramework & setIdleConnectionTimeout(size_t timeout)=0
Set the lifetime of the connection without read or write.

◆ setIdleConnectionTimeout() [2/2]

virtual HttpAppFramework & drogon::HttpAppFramework::setIdleConnectionTimeout ( size_t timeout)
pure virtual

Set the lifetime of the connection without read or write.

Parameters
timeoutin seconds. 60 by default. Setting the timeout to 0 means that drogon does not close idle connections.
Note
This operation can be performed by an option in the configuration file.

◆ setImplicitPage()

virtual HttpAppFramework & drogon::HttpAppFramework::setImplicitPage ( const std::string & implicitPageFile)
pure virtual

Set the page which would the server load in if it detects that the user requested a directory.

Set the HTML file that a directory would resolve to by default, default is "index.html"

Note
This operation can be performed by an option in the configuration file.

◆ setImplicitPageEnable()

virtual HttpAppFramework & drogon::HttpAppFramework::setImplicitPageEnable ( bool useImplicitPage)
pure virtual

Set to enable implicit pages, enabled by default.

Implicit pages are used when the server detects if the user requested a directory. By default, it will try to append index.html to the path, see setImplicitPage() if you want to customize this (http://localhost/a-directory resolves to http://localhost/a-directory/index.html by default).

Note
This operation can be performed by an option in the configuration file.

◆ setIntSignalHandler()

virtual HttpAppFramework & drogon::HttpAppFramework::setIntSignalHandler ( const std::function< void()> & handler)
pure virtual

Set the INT Signal Handler. This method provides a way to users for exiting program gracefully. When the INT signal is received after app().run() is called, the handler is invoked. Drogon uses a default signal handler for the INT signal, which calls the 'app().quit()' method when the INT signal is received.

Parameters
handler
Returns
HttpAppFramework&

◆ setJsonParserStackLimit()

virtual HttpAppFramework & drogon::HttpAppFramework::setJsonParserStackLimit ( size_t limit)
pure virtualnoexcept

Set the maximum stack depth of the json parser when reading a json string, the default value is 1000.

Note
This operation can be performed by an option in the configuration file.

◆ setKeepaliveRequestsNumber()

virtual HttpAppFramework & drogon::HttpAppFramework::setKeepaliveRequestsNumber ( const size_t number)
pure virtual

Set the maximum number of requests that can be served through one keep-alive connection. After the maximum number of requests are made, the connection is closed. The default value is 0 which means no limit.

Note
This operation can be performed by an option in the configuration file.

◆ setLogLevel()

virtual HttpAppFramework & drogon::HttpAppFramework::setLogLevel ( trantor::Logger::LogLevel level)
pure virtual

Set the log level.

Parameters
levelis one of TRACE, DEBUG, INFO, WARN. The Default value is DEBUG.
Note
This operation can be performed by an option in the configuration file.

◆ setLogLocalTime()

virtual HttpAppFramework & drogon::HttpAppFramework::setLogLocalTime ( bool on)
pure virtual

Set the log time display.

Parameters
onis true to display local time, false to display UTC time. The Default value is false.
Note
This operation can be performed by an option in the configuration file.

◆ setLogPath()

virtual HttpAppFramework & drogon::HttpAppFramework::setLogPath ( const std::string & logPath,
const std::string & logfileBaseName = "",
size_t logSize = 100000000,
size_t maxFiles = 0,
bool useSpdlog = false )
pure virtual

Set the output path of logs.

Parameters
logPathThe path to logs - logs to console if empty.
logfileBaseNameThe base name of log files - defaults to "drogon" if empty.
logSizeindicates the maximum size of a log file.
maxFilesmax count of log file - 0 = unlimited.
useSpdlogUse spdlog for logging (if compiled-in).
Note
This operation can be performed by an option in the configuration file.

◆ setMaxConnectionNum()

virtual HttpAppFramework & drogon::HttpAppFramework::setMaxConnectionNum ( size_t maxConnections)
pure virtual

Set the maximum number of all connections.

The default value is 100000.

Note
This operation can be performed by an option in the configuration file.

◆ setMaxConnectionNumPerIP()

virtual HttpAppFramework & drogon::HttpAppFramework::setMaxConnectionNumPerIP ( size_t maxConnectionsPerIP)
pure virtual

Set the maximum number of connections per remote IP.

The default value is 0 which means no limit.

Note
This operation can be performed by an option in the configuration file.

◆ setPipeliningRequestsNumber()

virtual HttpAppFramework & drogon::HttpAppFramework::setPipeliningRequestsNumber ( const size_t number)
pure virtual

Set the maximum number of unhandled requests that can be cached in pipelining buffer. The default value of 0 means no limit. After the maximum number of requests cached in pipelining buffer are made, the connection is closed.

Note
This operation can be performed by an option in the configuration file.

◆ setServerHeaderField()

virtual HttpAppFramework & drogon::HttpAppFramework::setServerHeaderField ( const std::string & server)
pure virtual

Set the 'server' header field in each response sent by drogon.

Parameters
serverempty string by default with which the 'server' header field is set to "Server: drogon/version string\r\n"
Note
This operation can be performed by an option in the configuration file.

◆ setSSLConfigCommands()

virtual HttpAppFramework & drogon::HttpAppFramework::setSSLConfigCommands ( const std::vector< std::pair< std::string, std::string > > & sslConfCmds)
pure virtual

Supplies file style SSL options to SSL_CONF_cmd. Valid options are available at https://www.openssl.org/docs/manmaster/man3/SSL_CONF_cmd.html

◆ setSSLFiles()

virtual HttpAppFramework & drogon::HttpAppFramework::setSSLFiles ( const std::string & certPath,
const std::string & keyPath )
pure virtual

Set the global cert file and private key file for https These options can be configured in the configuration file.

◆ setStaticFileHeaders()

virtual HttpAppFramework & drogon::HttpAppFramework::setStaticFileHeaders ( const std::vector< std::pair< std::string, std::string > > & headers)
pure virtual

Set the Static File Headers.

Parameters
headersEach pair object in the vector presents the field name and field value of a header in an static file response.

◆ setStaticFilesCacheTime()

virtual HttpAppFramework & drogon::HttpAppFramework::setStaticFilesCacheTime ( int cacheTime)
pure virtual

Set the time in which the static file response is cached in memory.

Parameters
cacheTimein seconds. 0 means always cached, negative means no cache
Note
This operation can be performed by an option in the configuration file.

◆ setTermSignalHandler()

virtual HttpAppFramework & drogon::HttpAppFramework::setTermSignalHandler ( const std::function< void()> & handler)
pure virtual

Set the TERM Signal Handler. This method provides a way to users for exiting program gracefully. When the TERM signal is received after app().run() is called, the handler is invoked. Drogon uses a default signal handler for the TERM signal, which calls the 'app().quit()' method when the TERM signal is received.

Parameters
handler
Returns
HttpAppFramework&

◆ setThreadNum()

virtual HttpAppFramework & drogon::HttpAppFramework::setThreadNum ( size_t threadNum)
pure virtual

Set the number of threads for IO event loops.

Parameters
threadNumthe number of threads The default value is 1, if the parameter is 0, the number is equal to the number of CPU cores.
Note
This number is usually less than or equal to the number of CPU cores. This number can be configured in the configuration file.

◆ setupFileLogger()

virtual HttpAppFramework & drogon::HttpAppFramework::setupFileLogger ( )
pure virtual

Setup output of logs to files.

Note
Logs are output to the standard output by default. Logging is setuped only if output path of logs is defined. This method is called in run() function, hence use this method only if you want to setup logging earlier.
Returns
HttpAppFramework&

◆ setUploadPath()

virtual HttpAppFramework & drogon::HttpAppFramework::setUploadPath ( const std::string & uploadPath)
pure virtual

Set the path to store uploaded files.

Parameters
uploadPathis the directory where the uploaded files are stored. if it isn't prefixed with /, ./ or ../, it is relative path of document_root path, The default value is 'uploads'.
Note
This operation can be performed by an option in the configuration file.

The documentation for this class was generated from the following file: