Make the framework API support chained calls (#223)

This commit is contained in:
An Tao 2019-08-24 14:44:25 +08:00 committed by GitHub
parent c3cb70f415
commit 043c484a64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 238 additions and 158 deletions

View File

@ -109,7 +109,7 @@ class HttpAppFramework : public trantor::NonCopyable
* After calling this method, the @param resp object is returned * After calling this method, the @param resp object is returned
* by the HttpResponse::newNotFoundResponse() method. * by the HttpResponse::newNotFoundResponse() method.
*/ */
virtual void setCustom404Page(const HttpResponsePtr &resp) = 0; virtual HttpAppFramework &setCustom404Page(const HttpResponsePtr &resp) = 0;
/// Get the plugin object registered in the framework /// Get the plugin object registered in the framework
/** /**
@ -142,7 +142,7 @@ class HttpAppFramework : public trantor::NonCopyable
/// The following is a series of methods of AOP /// The following is a series of methods of AOP
/// The @param advice is called immediately after the main event loop runs. /// The @param advice is called immediately after the main event loop runs.
virtual void registerBeginningAdvice( virtual HttpAppFramework &registerBeginningAdvice(
const std::function<void()> &advice) = 0; const std::function<void()> &advice) = 0;
/// The @param advice is called immediately when a new connection is /// The @param advice is called immediately when a new connection is
@ -154,7 +154,7 @@ class HttpAppFramework : public trantor::NonCopyable
* If the @param advice returns a false value, drogon closes the connection. * If the @param advice returns a false value, drogon closes the connection.
* Users can use this advice to implement some security policies. * Users can use this advice to implement some security policies.
*/ */
virtual void registerNewConnectionAdvice( virtual HttpAppFramework &registerNewConnectionAdvice(
const std::function<bool(const trantor::InetAddress &, const std::function<bool(const trantor::InetAddress &,
const trantor::InetAddress &)> &advice) = 0; const trantor::InetAddress &)> &advice) = 0;
@ -199,7 +199,7 @@ class HttpAppFramework : public trantor::NonCopyable
*Post-handling join point o---------------------------------------->+ *Post-handling join point o---------------------------------------->+
* *
*/ */
virtual void registerPreRoutingAdvice( virtual HttpAppFramework &registerPreRoutingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
AdviceCallback &&, AdviceCallback &&,
AdviceChainCallback &&)> &advice) = 0; AdviceChainCallback &&)> &advice) = 0;
@ -212,7 +212,7 @@ class HttpAppFramework : public trantor::NonCopyable
* If one does not intend to intercept the http request, please use this * If one does not intend to intercept the http request, please use this
* interface. * interface.
*/ */
virtual void registerPreRoutingAdvice( virtual HttpAppFramework &registerPreRoutingAdvice(
const std::function<void(const HttpRequestPtr &)> &advice) = 0; const std::function<void(const HttpRequestPtr &)> &advice) = 0;
/// The @param advice is called immediately after the request matchs a /// The @param advice is called immediately after the request matchs a
@ -221,7 +221,7 @@ class HttpAppFramework : public trantor::NonCopyable
* The parameters of the @param advice are same as those of the doFilter * The parameters of the @param advice are same as those of the doFilter
* method of the Filter class. * method of the Filter class.
*/ */
virtual void registerPostRoutingAdvice( virtual HttpAppFramework &registerPostRoutingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
AdviceCallback &&, AdviceCallback &&,
AdviceChainCallback &&)> &advice) = 0; AdviceChainCallback &&)> &advice) = 0;
@ -234,7 +234,7 @@ class HttpAppFramework : public trantor::NonCopyable
* If one does not intend to intercept the http request, please use this * If one does not intend to intercept the http request, please use this
* interface. * interface.
*/ */
virtual void registerPostRoutingAdvice( virtual HttpAppFramework &registerPostRoutingAdvice(
const std::function<void(const HttpRequestPtr &)> &advice) = 0; const std::function<void(const HttpRequestPtr &)> &advice) = 0;
/// The @param advice is called immediately after the request is approved by /// The @param advice is called immediately after the request is approved by
@ -243,7 +243,7 @@ class HttpAppFramework : public trantor::NonCopyable
* The parameters of the @param advice are same as those of the doFilter * The parameters of the @param advice are same as those of the doFilter
* method of the Filter class. * method of the Filter class.
*/ */
virtual void registerPreHandlingAdvice( virtual HttpAppFramework &registerPreHandlingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
AdviceCallback &&, AdviceCallback &&,
AdviceChainCallback &&)> &advice) = 0; AdviceChainCallback &&)> &advice) = 0;
@ -255,19 +255,19 @@ class HttpAppFramework : public trantor::NonCopyable
* If one does not intend to intercept the http request, please use this * If one does not intend to intercept the http request, please use this
* interface. * interface.
*/ */
virtual void registerPreHandlingAdvice( virtual HttpAppFramework &registerPreHandlingAdvice(
const std::function<void(const HttpRequestPtr &)> &advice) = 0; const std::function<void(const HttpRequestPtr &)> &advice) = 0;
/// The @param advice is called immediately after the request is handled and /// The @param advice is called immediately after the request is handled and
/// a response object is created by handlers. /// a response object is created by handlers.
virtual void registerPostHandlingAdvice( virtual HttpAppFramework &registerPostHandlingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
const HttpResponsePtr &)> &advice) = 0; const HttpResponsePtr &)> &advice) = 0;
/// End of AOP methods /// End of AOP methods
/// Load the configuration file with json format. /// Load the configuration file with json format.
virtual void loadConfigFile(const std::string &fileName) = 0; virtual HttpAppFramework &loadConfigFile(const std::string &fileName) = 0;
/// Register a HttpSimpleController object into the framework. /// Register a HttpSimpleController object into the framework.
/** /**
@ -286,7 +286,7 @@ class HttpAppFramework : public trantor::NonCopyable
* Users can perform the same operation through the configuration file or a * Users can perform the same operation through the configuration file or a
* macro in the header file. * macro in the header file.
*/ */
virtual void registerHttpSimpleController( virtual HttpAppFramework &registerHttpSimpleController(
const std::string &pathName, const std::string &pathName,
const std::string &ctrlName, const std::string &ctrlName,
const std::vector<internal::HttpConstraint> &filtersAndMethods = const std::vector<internal::HttpConstraint> &filtersAndMethods =
@ -323,7 +323,7 @@ class HttpAppFramework : public trantor::NonCopyable
* mapping. * mapping.
*/ */
template <typename FUNCTION> template <typename FUNCTION>
void registerHandler( HttpAppFramework &registerHandler(
const std::string &pathPattern, const std::string &pathPattern,
FUNCTION &&function, FUNCTION &&function,
const std::vector<internal::HttpConstraint> &filtersAndMethods = const std::vector<internal::HttpConstraint> &filtersAndMethods =
@ -357,12 +357,13 @@ class HttpAppFramework : public trantor::NonCopyable
} }
registerHttpController( registerHttpController(
pathPattern, binder, validMethods, filters, handlerName); pathPattern, binder, validMethods, filters, handlerName);
return *this;
} }
/// Register a WebSocketController into the framework. /// Register a WebSocketController into the framework.
/// The parameters of this method are the same as those in the /// The parameters of this method are the same as those in the
/// registerHttpSimpleController() method. /// registerHttpSimpleController() method.
virtual void registerWebSocketController( virtual HttpAppFramework &registerWebSocketController(
const std::string &pathName, const std::string &pathName,
const std::string &crtlName, const std::string &crtlName,
const std::vector<std::string> &filters = const std::vector<std::string> &filters =
@ -394,7 +395,7 @@ class HttpAppFramework : public trantor::NonCopyable
* This method should be called before calling the app().run() method. * This method should be called before calling the app().run() method.
*/ */
template <typename T> template <typename T>
void registerController(const std::shared_ptr<T> &ctrlPtr) HttpAppFramework &registerController(const std::shared_ptr<T> &ctrlPtr)
{ {
static_assert( static_assert(
internal::IsSubClass<T, HttpControllerBase>::value || internal::IsSubClass<T, HttpControllerBase>::value ||
@ -407,6 +408,7 @@ class HttpAppFramework : public trantor::NonCopyable
"registered here"); "registered here");
DrClassMap::setSingleInstance(ctrlPtr); DrClassMap::setSingleInstance(ctrlPtr);
T::initPathRouting(); T::initPathRouting();
return *this;
} }
/// Register filter objects created and initialized by the user /// Register filter objects created and initialized by the user
@ -414,7 +416,7 @@ class HttpAppFramework : public trantor::NonCopyable
* This method is similar to the above method. * This method is similar to the above method.
*/ */
template <typename T> template <typename T>
void registerFilter(const std::shared_ptr<T> &filterPtr) HttpAppFramework &registerFilter(const std::shared_ptr<T> &filterPtr)
{ {
static_assert(internal::IsSubClass<T, HttpFilterBase>::value, static_assert(internal::IsSubClass<T, HttpFilterBase>::value,
"Error! Only fitler objects can be registered here"); "Error! Only fitler objects can be registered here");
@ -423,6 +425,7 @@ class HttpAppFramework : public trantor::NonCopyable
"automatically by drogon cannot be " "automatically by drogon cannot be "
"registered here"); "registered here");
DrClassMap::setSingleInstance(filterPtr); DrClassMap::setSingleInstance(filterPtr);
return *this;
} }
/// Forward the http request /// Forward the http request
@ -471,14 +474,14 @@ class HttpAppFramework : public trantor::NonCopyable
* This number is usually less than or equal to the number of CPU cores. * This number is usually less than or equal to the number of CPU cores.
* This number can be configured in the configuration file. * This number can be configured in the configuration file.
*/ */
virtual void setThreadNum(size_t threadNum) = 0; virtual HttpAppFramework &setThreadNum(size_t threadNum) = 0;
/// Get the number of threads for IO event loops /// Get the number of threads for IO event loops
virtual size_t getThreadNum() const = 0; virtual size_t getThreadNum() const = 0;
/// Set the global cert file and private key file for https /// Set the global cert file and private key file for https
/// These options can be configured in the configuration file. /// These options can be configured in the configuration file.
virtual void setSSLFiles(const std::string &certPath, virtual HttpAppFramework &setSSLFiles(const std::string &certPath,
const std::string &keyPath) = 0; const std::string &keyPath) = 0;
/// Add a listener for http or https service /// Add a listener for http or https service
@ -493,7 +496,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void addListener(const std::string &ip, virtual HttpAppFramework &addListener(const std::string &ip,
uint16_t port, uint16_t port,
bool useSSL = false, bool useSSL = false,
const std::string &certFile = "", const std::string &certFile = "",
@ -509,7 +512,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void enableSession(const size_t timeout = 0) = 0; virtual HttpAppFramework &enableSession(const size_t timeout = 0) = 0;
/// A wrapper of the above method. /// A wrapper of the above method.
/** /**
@ -517,9 +520,10 @@ class HttpAppFramework : public trantor::NonCopyable
* app().enableSession(0.2h); * app().enableSession(0.2h);
* app().enableSession(12min); * app().enableSession(12min);
*/ */
inline void enableSession(const std::chrono::duration<long double> &timeout) inline HttpAppFramework &enableSession(
const std::chrono::duration<long double> &timeout)
{ {
enableSession((size_t)timeout.count()); return enableSession((size_t)timeout.count());
} }
/// Disable sessions supporting. /// Disable sessions supporting.
@ -527,14 +531,14 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void disableSession() = 0; virtual HttpAppFramework &disableSession() = 0;
/// Set the root path of HTTP document, defaut path is ./ /// Set the root path of HTTP document, defaut path is ./
/** /**
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setDocumentRoot(const std::string &rootPath) = 0; virtual HttpAppFramework &setDocumentRoot(const std::string &rootPath) = 0;
/// Get the document root directory. /// Get the document root directory.
virtual const std::string &getDocumentRoot() const = 0; virtual const std::string &getDocumentRoot() const = 0;
@ -548,7 +552,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setUploadPath(const std::string &uploadPath) = 0; virtual HttpAppFramework &setUploadPath(const std::string &uploadPath) = 0;
/// Get the path to store uploaded files. /// Get the path to store uploaded files.
virtual const std::string &getUploadPath() const = 0; virtual const std::string &getUploadPath() const = 0;
@ -561,7 +565,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setFileTypes(const std::vector<std::string> &types) = 0; virtual HttpAppFramework &setFileTypes(
const std::vector<std::string> &types) = 0;
/// Enable supporting for dynamic views loading. /// Enable supporting for dynamic views loading.
/** /**
@ -571,7 +576,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void enableDynamicViewsLoading( virtual HttpAppFramework &enableDynamicViewsLoading(
const std::vector<std::string> &libPaths) = 0; const std::vector<std::string> &libPaths) = 0;
/// Set the maximum number of all connections. /// Set the maximum number of all connections.
@ -581,7 +586,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setMaxConnectionNum(size_t maxConnections) = 0; virtual HttpAppFramework &setMaxConnectionNum(size_t maxConnections) = 0;
/// Set the maximum number of connections per remote IP. /// Set the maximum number of connections per remote IP.
/** /**
@ -590,7 +595,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setMaxConnectionNumPerIP(size_t maxConnectionsPerIP) = 0; virtual HttpAppFramework &setMaxConnectionNumPerIP(
size_t maxConnectionsPerIP) = 0;
/// Make the application run as a daemon. /// Make the application run as a daemon.
/** /**
@ -599,7 +605,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void enableRunAsDaemon() = 0; virtual HttpAppFramework &enableRunAsDaemon() = 0;
/// Make the application restart after crashing. /// Make the application restart after crashing.
/** /**
@ -608,7 +614,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void enableRelaunchOnError() = 0; virtual HttpAppFramework &enableRelaunchOnError() = 0;
/// Set the output path of logs. /// Set the output path of logs.
/** /**
@ -617,7 +623,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setLogPath(const std::string &logPath, virtual HttpAppFramework &setLogPath(
const std::string &logPath,
const std::string &logfileBaseName = "", const std::string &logfileBaseName = "",
size_t logSize = 100000000) = 0; size_t logSize = 100000000) = 0;
@ -629,7 +636,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setLogLevel(trantor::Logger::LogLevel level) = 0; virtual HttpAppFramework &setLogLevel(trantor::Logger::LogLevel level) = 0;
/// If @param sendFile is true, sendfile() system-call is used to send /// If @param sendFile is true, sendfile() system-call is used to send
/// static files to clients; /// static files to clients;
@ -643,7 +650,7 @@ class HttpAppFramework : public trantor::NonCopyable
* because the advantages of sendfile() can only be reflected in sending * because the advantages of sendfile() can only be reflected in sending
* large files. * large files.
*/ */
virtual void enableSendfile(bool sendFile) = 0; virtual HttpAppFramework &enableSendfile(bool sendFile) = 0;
/// If @param useGzip is true, use gzip to compress the response body's /// If @param useGzip is true, use gzip to compress the response body's
/// content; /// content;
@ -656,7 +663,7 @@ class HttpAppFramework : public trantor::NonCopyable
* 1. The content type of response is not a binary type. * 1. The content type of response is not a binary type.
* 2. The content length is bigger than 1024 bytes. * 2. The content length is bigger than 1024 bytes.
*/ */
virtual void enableGzip(bool useGzip) = 0; virtual HttpAppFramework &enableGzip(bool useGzip) = 0;
/// Return true if gzip is enabled. /// Return true if gzip is enabled.
virtual bool isGzipEnabled() const = 0; virtual bool isGzipEnabled() const = 0;
@ -669,7 +676,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setStaticFilesCacheTime(int cacheTime) = 0; virtual HttpAppFramework &setStaticFilesCacheTime(int cacheTime) = 0;
/// Get the time set by the above method. /// Get the time set by the above method.
virtual int staticFilesCacheTime() const = 0; virtual int staticFilesCacheTime() const = 0;
@ -682,7 +689,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setIdleConnectionTimeout(size_t timeout) = 0; virtual HttpAppFramework &setIdleConnectionTimeout(size_t timeout) = 0;
/// A wrapper of the above method. /// A wrapper of the above method.
/** /**
@ -690,10 +697,10 @@ class HttpAppFramework : public trantor::NonCopyable
* app().setIdleConnectionTimeout(0.5h); * app().setIdleConnectionTimeout(0.5h);
* app().setIdleConnectionTimeout(30min); * app().setIdleConnectionTimeout(30min);
*/ */
inline void setIdleConnectionTimeout( inline HttpAppFramework &setIdleConnectionTimeout(
const std::chrono::duration<long double> &timeout) const std::chrono::duration<long double> &timeout)
{ {
setIdleConnectionTimeout((size_t)timeout.count()); return setIdleConnectionTimeout((size_t)timeout.count());
} }
/// Set the 'server' header field in each response sent by drogon. /// Set the 'server' header field in each response sent by drogon.
@ -704,7 +711,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setServerHeaderField(const std::string &server) = 0; virtual HttpAppFramework &setServerHeaderField(
const std::string &server) = 0;
/// Control if the 'Server' header or the 'Date' header is added to each /// Control if the 'Server' header or the 'Date' header is added to each
/// HTTP response. /// HTTP response.
@ -713,8 +721,8 @@ class HttpAppFramework : public trantor::NonCopyable
* These operations can be performed by options in the configuration file. * These operations can be performed by options in the configuration file.
* The headers are sent to clients by default. * The headers are sent to clients by default.
*/ */
virtual void enableServerHeader(bool flag) = 0; virtual HttpAppFramework &enableServerHeader(bool flag) = 0;
virtual void enableDateHeader(bool flag) = 0; virtual HttpAppFramework &enableDateHeader(bool flag) = 0;
/// Set the maximum number of requests that can be served through one /// Set the maximum number of requests that can be served through one
/// keep-alive connection. /// keep-alive connection.
@ -725,7 +733,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setKeepaliveRequestsNumber(const size_t number) = 0; virtual HttpAppFramework &setKeepaliveRequestsNumber(
const size_t number) = 0;
/// Set the maximum number of unhandled requests that can be cached in /// Set the maximum number of unhandled requests that can be cached in
/// pipelining buffer. /// pipelining buffer.
@ -737,7 +746,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setPipeliningRequestsNumber(const size_t number) = 0; virtual HttpAppFramework &setPipeliningRequestsNumber(
const size_t number) = 0;
/// Set the gzip_static option. /// Set the gzip_static option.
/** /**
@ -748,7 +758,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setGzipStatic(bool useGzipStatic) = 0; virtual HttpAppFramework &setGzipStatic(bool useGzipStatic) = 0;
/// Set the max body size of the requests received by drogon. The default /// Set the max body size of the requests received by drogon. The default
/// value is 1M. /// value is 1M.
@ -756,7 +766,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setClientMaxBodySize(size_t maxSize) = 0; virtual HttpAppFramework &setClientMaxBodySize(size_t maxSize) = 0;
/// Set the maximum body size in memory of HTTP requests received by drogon. /// Set the maximum body size in memory of HTTP requests received by drogon.
/** /**
@ -767,7 +777,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setClientMaxMemoryBodySize(size_t maxSize) = 0; virtual HttpAppFramework &setClientMaxMemoryBodySize(size_t maxSize) = 0;
/// Set the max size of messages sent by WebSocket client. The default value /// Set the max size of messages sent by WebSocket client. The default value
/// is 128K. /// is 128K.
@ -775,7 +785,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setClientMaxWebSocketMessageSize(size_t maxSize) = 0; virtual HttpAppFramework &setClientMaxWebSocketMessageSize(
size_t maxSize) = 0;
// Set the HTML file of the home page, the default value is "index.html" // Set the HTML file of the home page, the default value is "index.html"
/** /**
@ -785,7 +796,7 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void setHomePage(const std::string &homePageFile) = 0; virtual HttpAppFramework &setHomePage(const std::string &homePageFile) = 0;
/// Get a database client by @param name /// Get a database client by @param name
/** /**
@ -819,7 +830,8 @@ class HttpAppFramework : public trantor::NonCopyable
* NOTE: * NOTE:
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual void createDbClient(const std::string &dbType, virtual HttpAppFramework &createDbClient(
const std::string &dbType,
const std::string &host, const std::string &host,
const u_short port, const u_short port,
const std::string &databaseName, const std::string &databaseName,

View File

@ -141,19 +141,21 @@ HttpAppFrameworkImpl::~HttpAppFrameworkImpl() noexcept
_sharedLibManagerPtr.reset(); _sharedLibManagerPtr.reset();
_sessionManagerPtr.reset(); _sessionManagerPtr.reset();
} }
void HttpAppFrameworkImpl::setStaticFilesCacheTime(int cacheTime) HttpAppFramework &HttpAppFrameworkImpl::setStaticFilesCacheTime(int cacheTime)
{ {
_staticFileRouterPtr->setStaticFilesCacheTime(cacheTime); _staticFileRouterPtr->setStaticFilesCacheTime(cacheTime);
return *this;
} }
int HttpAppFrameworkImpl::staticFilesCacheTime() const int HttpAppFrameworkImpl::staticFilesCacheTime() const
{ {
return _staticFileRouterPtr->staticFilesCacheTime(); return _staticFileRouterPtr->staticFilesCacheTime();
} }
void HttpAppFrameworkImpl::setGzipStatic(bool useGzipStatic) HttpAppFramework &HttpAppFrameworkImpl::setGzipStatic(bool useGzipStatic)
{ {
_staticFileRouterPtr->setGzipStatic(useGzipStatic); _staticFileRouterPtr->setGzipStatic(useGzipStatic);
return *this;
} }
void HttpAppFrameworkImpl::enableDynamicViewsLoading( HttpAppFramework &HttpAppFrameworkImpl::enableDynamicViewsLoading(
const std::vector<std::string> &libPaths) const std::vector<std::string> &libPaths)
{ {
assert(!_running); assert(!_running);
@ -176,13 +178,16 @@ void HttpAppFrameworkImpl::enableDynamicViewsLoading(
_libFilePaths.push_back(_rootPath + "/" + libpath); _libFilePaths.push_back(_rootPath + "/" + libpath);
} }
} }
return *this;
} }
void HttpAppFrameworkImpl::setFileTypes(const std::vector<std::string> &types) HttpAppFramework &HttpAppFrameworkImpl::setFileTypes(
const std::vector<std::string> &types)
{ {
_staticFileRouterPtr->setFileTypes(types); _staticFileRouterPtr->setFileTypes(types);
return *this;
} }
void HttpAppFrameworkImpl::registerWebSocketController( HttpAppFramework &HttpAppFrameworkImpl::registerWebSocketController(
const std::string &pathName, const std::string &pathName,
const std::string &ctrlName, const std::string &ctrlName,
const std::vector<std::string> &filters) const std::vector<std::string> &filters)
@ -191,8 +196,9 @@ void HttpAppFrameworkImpl::registerWebSocketController(
_websockCtrlsRouterPtr->registerWebSocketController(pathName, _websockCtrlsRouterPtr->registerWebSocketController(pathName,
ctrlName, ctrlName,
filters); filters);
return *this;
} }
void HttpAppFrameworkImpl::registerHttpSimpleController( HttpAppFramework &HttpAppFrameworkImpl::registerHttpSimpleController(
const std::string &pathName, const std::string &pathName,
const std::string &ctrlName, const std::string &ctrlName,
const std::vector<internal::HttpConstraint> &filtersAndMethods) const std::vector<internal::HttpConstraint> &filtersAndMethods)
@ -201,6 +207,7 @@ void HttpAppFrameworkImpl::registerHttpSimpleController(
_httpSimpleCtrlsRouterPtr->registerHttpSimpleController(pathName, _httpSimpleCtrlsRouterPtr->registerHttpSimpleController(pathName,
ctrlName, ctrlName,
filtersAndMethods); filtersAndMethods);
return *this;
} }
void HttpAppFrameworkImpl::registerHttpController( void HttpAppFrameworkImpl::registerHttpController(
@ -216,16 +223,17 @@ void HttpAppFrameworkImpl::registerHttpController(
_httpCtrlsRouterPtr->addHttpPath( _httpCtrlsRouterPtr->addHttpPath(
pathPattern, binder, validMethods, filters, handlerName); pathPattern, binder, validMethods, filters, handlerName);
} }
void HttpAppFrameworkImpl::setThreadNum(size_t threadNum) HttpAppFramework &HttpAppFrameworkImpl::setThreadNum(size_t threadNum)
{ {
assert(threadNum >= 1); assert(threadNum >= 1);
_threadNum = threadNum; _threadNum = threadNum;
return *this;
} }
PluginBase *HttpAppFrameworkImpl::getPlugin(const std::string &name) PluginBase *HttpAppFrameworkImpl::getPlugin(const std::string &name)
{ {
return _pluginsManagerPtr->getPlugin(name); return _pluginsManagerPtr->getPlugin(name);
} }
void HttpAppFrameworkImpl::addListener(const std::string &ip, HttpAppFramework &HttpAppFrameworkImpl::addListener(const std::string &ip,
uint16_t port, uint16_t port,
bool useSSL, bool useSSL,
const std::string &certFile, const std::string &certFile,
@ -233,27 +241,35 @@ void HttpAppFrameworkImpl::addListener(const std::string &ip,
{ {
assert(!_running); assert(!_running);
_listenerManagerPtr->addListener(ip, port, useSSL, certFile, keyFile); _listenerManagerPtr->addListener(ip, port, useSSL, certFile, keyFile);
return *this;
} }
void HttpAppFrameworkImpl::setMaxConnectionNum(size_t maxConnections) HttpAppFramework &HttpAppFrameworkImpl::setMaxConnectionNum(
size_t maxConnections)
{ {
_maxConnectionNum = maxConnections; _maxConnectionNum = maxConnections;
return *this;
} }
void HttpAppFrameworkImpl::setMaxConnectionNumPerIP(size_t maxConnectionsPerIP) HttpAppFramework &HttpAppFrameworkImpl::setMaxConnectionNumPerIP(
size_t maxConnectionsPerIP)
{ {
_maxConnectionNumPerIP = maxConnectionsPerIP; _maxConnectionNumPerIP = maxConnectionsPerIP;
return *this;
} }
void HttpAppFrameworkImpl::loadConfigFile(const std::string &fileName) HttpAppFramework &HttpAppFrameworkImpl::loadConfigFile(
const std::string &fileName)
{ {
ConfigLoader loader(fileName); ConfigLoader loader(fileName);
loader.load(); loader.load();
_jsonConfig = loader.jsonValue(); _jsonConfig = loader.jsonValue();
return *this;
} }
void HttpAppFrameworkImpl::setLogPath(const std::string &logPath, HttpAppFramework &HttpAppFrameworkImpl::setLogPath(
const std::string &logPath,
const std::string &logfileBaseName, const std::string &logfileBaseName,
size_t logfileSize) size_t logfileSize)
{ {
if (logPath == "") if (logPath == "")
return; return *this;
if (access(logPath.c_str(), 0) != 0) if (access(logPath.c_str(), 0) != 0)
{ {
std::cerr << "Log path dose not exist!\n"; std::cerr << "Log path dose not exist!\n";
@ -267,16 +283,20 @@ void HttpAppFrameworkImpl::setLogPath(const std::string &logPath,
_logPath = logPath; _logPath = logPath;
_logfileBaseName = logfileBaseName; _logfileBaseName = logfileBaseName;
_logfileSize = logfileSize; _logfileSize = logfileSize;
return *this;
} }
void HttpAppFrameworkImpl::setLogLevel(trantor::Logger::LogLevel level) HttpAppFramework &HttpAppFrameworkImpl::setLogLevel(
trantor::Logger::LogLevel level)
{ {
trantor::Logger::setLogLevel(level); trantor::Logger::setLogLevel(level);
return *this;
} }
void HttpAppFrameworkImpl::setSSLFiles(const std::string &certPath, HttpAppFramework &HttpAppFrameworkImpl::setSSLFiles(const std::string &certPath,
const std::string &keyPath) const std::string &keyPath)
{ {
_sslCertPath = certPath; _sslCertPath = certPath;
_sslKeyPath = keyPath; _sslKeyPath = keyPath;
return *this;
} }
void HttpAppFrameworkImpl::run() void HttpAppFrameworkImpl::run()
@ -467,7 +487,8 @@ void HttpAppFrameworkImpl::onConnection(const trantor::TcpConnectionPtr &conn)
} }
} }
void HttpAppFrameworkImpl::setUploadPath(const std::string &uploadPath) HttpAppFramework &HttpAppFrameworkImpl::setUploadPath(
const std::string &uploadPath)
{ {
assert(!uploadPath.empty()); assert(!uploadPath.empty());
if (uploadPath[0] == '/' || if (uploadPath[0] == '/' ||
@ -486,6 +507,7 @@ void HttpAppFrameworkImpl::setUploadPath(const std::string &uploadPath)
else else
_uploadPath = _rootPath + "/" + uploadPath; _uploadPath = _rootPath + "/" + uploadPath;
} }
return *this;
} }
void HttpAppFrameworkImpl::onNewWebsockRequest( void HttpAppFrameworkImpl::onNewWebsockRequest(
const HttpRequestImplPtr &req, const HttpRequestImplPtr &req,
@ -688,7 +710,8 @@ orm::DbClientPtr HttpAppFrameworkImpl::getFastDbClient(const std::string &name)
{ {
return _dbClientManagerPtr->getFastDbClient(name); return _dbClientManagerPtr->getFastDbClient(name);
} }
void HttpAppFrameworkImpl::createDbClient(const std::string &dbType, HttpAppFramework &HttpAppFrameworkImpl::createDbClient(
const std::string &dbType,
const std::string &host, const std::string &host,
const u_short port, const u_short port,
const std::string &databaseName, const std::string &databaseName,
@ -710,4 +733,5 @@ void HttpAppFrameworkImpl::createDbClient(const std::string &dbType,
filename, filename,
name, name,
isFast); isFast);
return *this;
} }

View File

@ -44,34 +44,37 @@ class HttpAppFrameworkImpl : public HttpAppFramework
} }
virtual PluginBase *getPlugin(const std::string &name) override; virtual PluginBase *getPlugin(const std::string &name) override;
virtual void addListener(const std::string &ip, virtual HttpAppFramework &addListener(
const std::string &ip,
uint16_t port, uint16_t port,
bool useSSL = false, bool useSSL = false,
const std::string &certFile = "", const std::string &certFile = "",
const std::string &keyFile = "") override; const std::string &keyFile = "") override;
virtual void setThreadNum(size_t threadNum) override; virtual HttpAppFramework &setThreadNum(size_t threadNum) override;
virtual size_t getThreadNum() const override virtual size_t getThreadNum() const override
{ {
return _threadNum; return _threadNum;
} }
virtual void setSSLFiles(const std::string &certPath, virtual HttpAppFramework &setSSLFiles(const std::string &certPath,
const std::string &keyPath) override; const std::string &keyPath) override;
virtual void run() override; virtual void run() override;
virtual void registerWebSocketController( virtual HttpAppFramework &registerWebSocketController(
const std::string &pathName, const std::string &pathName,
const std::string &crtlName, const std::string &crtlName,
const std::vector<std::string> &filters = const std::vector<std::string> &filters =
std::vector<std::string>()) override; std::vector<std::string>()) override;
virtual void registerHttpSimpleController( virtual HttpAppFramework &registerHttpSimpleController(
const std::string &pathName, const std::string &pathName,
const std::string &crtlName, const std::string &crtlName,
const std::vector<internal::HttpConstraint> &filtersAndMethods = const std::vector<internal::HttpConstraint> &filtersAndMethods =
std::vector<internal::HttpConstraint>{}) override; std::vector<internal::HttpConstraint>{}) override;
virtual void setCustom404Page(const HttpResponsePtr &resp) override virtual HttpAppFramework &setCustom404Page(
const HttpResponsePtr &resp) override
{ {
resp->setStatusCode(k404NotFound); resp->setStatusCode(k404NotFound);
_custom404 = resp; _custom404 = resp;
return *this;
} }
const HttpResponsePtr &getCustom404Page() const HttpResponsePtr &getCustom404Page()
@ -88,80 +91,93 @@ class HttpAppFrameworkImpl : public HttpAppFramework
std::function<void(const HttpResponsePtr &)> &&callback, std::function<void(const HttpResponsePtr &)> &&callback,
const std::string &hostString); const std::string &hostString);
virtual void registerBeginningAdvice( virtual HttpAppFramework &registerBeginningAdvice(
const std::function<void()> &advice) override const std::function<void()> &advice) override
{ {
getLoop()->runInLoop(advice); getLoop()->runInLoop(advice);
return *this;
} }
virtual void registerNewConnectionAdvice( virtual HttpAppFramework &registerNewConnectionAdvice(
const std::function<bool(const trantor::InetAddress &, const std::function<bool(const trantor::InetAddress &,
const trantor::InetAddress &)> &advice) const trantor::InetAddress &)> &advice)
override override
{ {
_newConnectionAdvices.emplace_back(advice); _newConnectionAdvices.emplace_back(advice);
return *this;
} }
virtual void registerPreRoutingAdvice( virtual HttpAppFramework &registerPreRoutingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
AdviceCallback &&, AdviceCallback &&,
AdviceChainCallback &&)> &advice) override AdviceChainCallback &&)> &advice) override
{ {
_preRoutingAdvices.emplace_back(advice); _preRoutingAdvices.emplace_back(advice);
return *this;
} }
virtual void registerPostRoutingAdvice( virtual HttpAppFramework &registerPostRoutingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
AdviceCallback &&, AdviceCallback &&,
AdviceChainCallback &&)> &advice) override AdviceChainCallback &&)> &advice) override
{ {
_postRoutingAdvices.emplace_back(advice); _postRoutingAdvices.emplace_back(advice);
return *this;
} }
virtual void registerPreHandlingAdvice( virtual HttpAppFramework &registerPreHandlingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
AdviceCallback &&, AdviceCallback &&,
AdviceChainCallback &&)> &advice) override AdviceChainCallback &&)> &advice) override
{ {
_preHandlingAdvices.emplace_back(advice); _preHandlingAdvices.emplace_back(advice);
return *this;
} }
virtual void registerPreRoutingAdvice( virtual HttpAppFramework &registerPreRoutingAdvice(
const std::function<void(const HttpRequestPtr &)> &advice) override const std::function<void(const HttpRequestPtr &)> &advice) override
{ {
_preRoutingObservers.emplace_back(advice); _preRoutingObservers.emplace_back(advice);
return *this;
} }
virtual void registerPostRoutingAdvice( virtual HttpAppFramework &registerPostRoutingAdvice(
const std::function<void(const HttpRequestPtr &)> &advice) override const std::function<void(const HttpRequestPtr &)> &advice) override
{ {
_postRoutingObservers.emplace_back(advice); _postRoutingObservers.emplace_back(advice);
return *this;
} }
virtual void registerPreHandlingAdvice( virtual HttpAppFramework &registerPreHandlingAdvice(
const std::function<void(const HttpRequestPtr &)> &advice) override const std::function<void(const HttpRequestPtr &)> &advice) override
{ {
_preHandlingObservers.emplace_back(advice); _preHandlingObservers.emplace_back(advice);
return *this;
} }
virtual void registerPostHandlingAdvice( virtual HttpAppFramework &registerPostHandlingAdvice(
const std::function<void(const HttpRequestPtr &, const std::function<void(const HttpRequestPtr &,
const HttpResponsePtr &)> &advice) override const HttpResponsePtr &)> &advice) override
{ {
_postHandlingAdvices.emplace_back(advice); _postHandlingAdvices.emplace_back(advice);
return *this;
} }
virtual void enableSession(const size_t timeout = 0) override virtual HttpAppFramework &enableSession(const size_t timeout = 0) override
{ {
_useSession = true; _useSession = true;
_sessionTimeout = timeout; _sessionTimeout = timeout;
return *this;
} }
virtual void disableSession() override virtual HttpAppFramework &disableSession() override
{ {
_useSession = false; _useSession = false;
return *this;
} }
virtual const std::string &getDocumentRoot() const override virtual const std::string &getDocumentRoot() const override
{ {
return _rootPath; return _rootPath;
} }
virtual void setDocumentRoot(const std::string &rootPath) override virtual HttpAppFramework &setDocumentRoot(
const std::string &rootPath) override
{ {
_rootPath = rootPath; _rootPath = rootPath;
return *this;
} }
virtual const std::string &getUploadPath() const override virtual const std::string &getUploadPath() const override
{ {
@ -173,67 +189,90 @@ class HttpAppFrameworkImpl : public HttpAppFramework
static auto resolver = trantor::Resolver::newResolver(getLoop()); static auto resolver = trantor::Resolver::newResolver(getLoop());
return resolver; return resolver;
} }
virtual void setUploadPath(const std::string &uploadPath) override; virtual HttpAppFramework &setUploadPath(
virtual void setFileTypes(const std::vector<std::string> &types) override; const std::string &uploadPath) override;
virtual void enableDynamicViewsLoading( virtual HttpAppFramework &setFileTypes(
const std::vector<std::string> &types) override;
virtual HttpAppFramework &enableDynamicViewsLoading(
const std::vector<std::string> &libPaths) override; const std::vector<std::string> &libPaths) override;
virtual void setMaxConnectionNum(size_t maxConnections) override; virtual HttpAppFramework &setMaxConnectionNum(
virtual void setMaxConnectionNumPerIP(size_t maxConnectionsPerIP) override; size_t maxConnections) override;
virtual void loadConfigFile(const std::string &fileName) override; virtual HttpAppFramework &setMaxConnectionNumPerIP(
virtual void enableRunAsDaemon() override size_t maxConnectionsPerIP) override;
virtual HttpAppFramework &loadConfigFile(
const std::string &fileName) override;
virtual HttpAppFramework &enableRunAsDaemon() override
{ {
_runAsDaemon = true; _runAsDaemon = true;
return *this;
} }
virtual void enableRelaunchOnError() override virtual HttpAppFramework &enableRelaunchOnError() override
{ {
_relaunchOnError = true; _relaunchOnError = true;
return *this;
} }
virtual void setLogPath(const std::string &logPath, virtual HttpAppFramework &setLogPath(
const std::string &logPath,
const std::string &logfileBaseName = "", const std::string &logfileBaseName = "",
size_t logfileSize = 100000000) override; size_t logfileSize = 100000000) override;
virtual void setLogLevel(trantor::Logger::LogLevel level) override; virtual HttpAppFramework &setLogLevel(
virtual void enableSendfile(bool sendFile) override trantor::Logger::LogLevel level) override;
virtual HttpAppFramework &enableSendfile(bool sendFile) override
{ {
_useSendfile = sendFile; _useSendfile = sendFile;
return *this;
} }
virtual void enableGzip(bool useGzip) override virtual HttpAppFramework &enableGzip(bool useGzip) override
{ {
_useGzip = useGzip; _useGzip = useGzip;
return *this;
} }
virtual bool isGzipEnabled() const override virtual bool isGzipEnabled() const override
{ {
return _useGzip; return _useGzip;
} }
virtual void setStaticFilesCacheTime(int cacheTime) override; virtual HttpAppFramework &setStaticFilesCacheTime(int cacheTime) override;
virtual int staticFilesCacheTime() const override; virtual int staticFilesCacheTime() const override;
virtual void setIdleConnectionTimeout(size_t timeout) override virtual HttpAppFramework &setIdleConnectionTimeout(size_t timeout) override
{ {
_idleConnectionTimeout = timeout; _idleConnectionTimeout = timeout;
return *this;
} }
virtual void setKeepaliveRequestsNumber(const size_t number) override virtual HttpAppFramework &setKeepaliveRequestsNumber(
const size_t number) override
{ {
_keepaliveRequestsNumber = number; _keepaliveRequestsNumber = number;
return *this;
} }
virtual void setPipeliningRequestsNumber(const size_t number) override virtual HttpAppFramework &setPipeliningRequestsNumber(
const size_t number) override
{ {
_pipeliningRequestsNumber = number; _pipeliningRequestsNumber = number;
return *this;
} }
virtual void setGzipStatic(bool useGzipStatic) override; virtual HttpAppFramework &setGzipStatic(bool useGzipStatic) override;
virtual void setClientMaxBodySize(size_t maxSize) override virtual HttpAppFramework &setClientMaxBodySize(size_t maxSize) override
{ {
_clientMaxBodySize = maxSize; _clientMaxBodySize = maxSize;
return *this;
} }
virtual void setClientMaxMemoryBodySize(size_t maxSize) override virtual HttpAppFramework &setClientMaxMemoryBodySize(
size_t maxSize) override
{ {
_clientMaxMemoryBodySize = maxSize; _clientMaxMemoryBodySize = maxSize;
return *this;
} }
virtual void setClientMaxWebSocketMessageSize(size_t maxSize) override virtual HttpAppFramework &setClientMaxWebSocketMessageSize(
size_t maxSize) override
{ {
_clientMaxWebSocketMessageSize = maxSize; _clientMaxWebSocketMessageSize = maxSize;
return *this;
} }
virtual void setHomePage(const std::string &homePageFile) override virtual HttpAppFramework &setHomePage(
const std::string &homePageFile) override
{ {
_homePageFile = homePageFile; _homePageFile = homePageFile;
return *this;
} }
const std::string &getHomePage() const const std::string &getHomePage() const
{ {
@ -277,20 +316,24 @@ class HttpAppFrameworkImpl : public HttpAppFramework
getLoop()->quit(); getLoop()->quit();
} }
virtual void setServerHeaderField(const std::string &server) override virtual HttpAppFramework &setServerHeaderField(
const std::string &server) override
{ {
assert(!_running); assert(!_running);
assert(server.find("\r\n") == std::string::npos); assert(server.find("\r\n") == std::string::npos);
_serverHeader = "Server: " + server + "\r\n"; _serverHeader = "Server: " + server + "\r\n";
return *this;
} }
virtual void enableServerHeader(bool flag) override virtual HttpAppFramework &enableServerHeader(bool flag) override
{ {
_enableServerHeader = flag; _enableServerHeader = flag;
return *this;
} }
virtual void enableDateHeader(bool flag) override virtual HttpAppFramework &enableDateHeader(bool flag) override
{ {
_enableDateHeader = flag; _enableDateHeader = flag;
return *this;
} }
bool sendServerHeader() const bool sendServerHeader() const
{ {
@ -309,7 +352,8 @@ class HttpAppFrameworkImpl : public HttpAppFramework
const std::string &name = "default") override; const std::string &name = "default") override;
virtual orm::DbClientPtr getFastDbClient( virtual orm::DbClientPtr getFastDbClient(
const std::string &name = "default") override; const std::string &name = "default") override;
virtual void createDbClient(const std::string &dbType, virtual HttpAppFramework &createDbClient(
const std::string &dbType,
const std::string &host, const std::string &host,
const u_short port, const u_short port,
const std::string &databaseName, const std::string &databaseName,