Rename HttpApiController to HttpController

This commit is contained in:
antao 2018-11-15 14:31:10 +08:00
parent 7d45746474
commit fd58a419a9
13 changed files with 88 additions and 89 deletions

View File

@ -25,8 +25,8 @@ std::string create::detail()
"drogon_ctl create view <csp file name> //create HttpView source files from csp file\n"
"drogon_ctl create controller [-s] [-n <namespace>] <class_name> //"
"create HttpSimpleController source files\n"
"drogon_ctl create controller -a <[namespace::]class_name> //"
"create HttpApiController source files\n"
"drogon_ctl create controller -h <[namespace::]class_name> //"
"create HttpController source files\n"
"drogon_ctl create controller -w [-n <namespace>] <class_name> //"
"create WebSocketController source files\n"
"drogon_ctl create project <project_name> //"

View File

@ -33,9 +33,9 @@ void create_controller::handleCommand(std::vector<std::string> &parameters)
parameters.erase(iter);
break;
}
else if (*iter == "-a" || *iter == "--api")
else if (*iter == "-a" || *iter == "-h" || *iter == "--http")
{
type = API;
type = Http;
parameters.erase(iter);
break;
}
@ -125,7 +125,7 @@ void create_controller::handleCommand(std::vector<std::string> &parameters)
createWebsockController(parameters, namespaceName);
}
else
createApiController(parameters);
createHttpController(parameters);
}
void create_controller::createSimpleController(std::vector<std::string> &ctlNames, const std::string &namespaceName)
@ -311,9 +311,9 @@ void create_controller::newWebsockControllerSourceFile(std::ofstream &file, cons
file << "}\n";
}
void create_controller::createApiController(std::vector<std::string> &apiClasses)
void create_controller::createHttpController(std::vector<std::string> &httpClasses)
{
for (auto iter = apiClasses.begin(); iter != apiClasses.end(); iter++)
for (auto iter = httpClasses.begin(); iter != httpClasses.end(); iter++)
{
if ((*iter)[0] == '-')
{
@ -321,31 +321,31 @@ void create_controller::createApiController(std::vector<std::string> &apiClasses
return;
}
}
for (auto className : apiClasses)
for (auto className : httpClasses)
{
createApiController(className);
createHttpController(className);
}
}
void create_controller::createApiController(const std::string &className)
void create_controller::createHttpController(const std::string &className)
{
std::regex regex("::");
std::string ctlName = std::regex_replace(className, regex, std::string("_"));
std::cout << "create api controller:" << className << std::endl;
std::cout << "create http controller:" << className << std::endl;
std::string headFileName = ctlName + ".h";
std::string sourceFilename = ctlName + ".cc";
std::ofstream oHeadFile(headFileName.c_str(), std::ofstream::out);
std::ofstream oSourceFile(sourceFilename.c_str(), std::ofstream::out);
if (!oHeadFile || !oSourceFile)
return;
newApiControllerHeaderFile(oHeadFile, className);
newApiControllerSourceFile(oSourceFile, className, ctlName);
newHttpControllerHeaderFile(oHeadFile, className);
newHttpControllerSourceFile(oSourceFile, className, ctlName);
}
void create_controller::newApiControllerHeaderFile(std::ofstream &file, const std::string &className)
void create_controller::newHttpControllerHeaderFile(std::ofstream &file, const std::string &className)
{
file << "#pragma once\n";
file << "#include <drogon/HttpApiController.h>\n";
file << "#include <drogon/HttpController.h>\n";
file << "using namespace drogon;\n";
std::string indent = "";
std::string class_name = className;
@ -361,7 +361,7 @@ void create_controller::newApiControllerHeaderFile(std::ofstream &file, const st
indent.append(" ");
pos = class_name.find("::");
}
file << indent << "class " << class_name << ":public drogon::HttpApiController<" << class_name << ">\n";
file << indent << "class " << class_name << ":public drogon::HttpController<" << class_name << ">\n";
file << indent << "{\n";
file << indent << "public:\n";
indent.append(" ");
@ -390,7 +390,7 @@ void create_controller::newApiControllerHeaderFile(std::ofstream &file, const st
file << indent << "}\n";
} while (indent != "");
}
void create_controller::newApiControllerSourceFile(std::ofstream &file, const std::string &className, const std::string &filename)
void create_controller::newHttpControllerSourceFile(std::ofstream &file, const std::string &className, const std::string &filename)
{
file << "#include \"" << filename << ".h\"\n";
auto pos = className.rfind("::");

View File

@ -29,7 +29,7 @@ class create_controller : public DrObject<create_controller>, public CommandHand
enum ControllerType
{
Simple = 0,
API,
Http,
WebSocket
};
void createSimpleController(std::vector<std::string> &ctlNames, const std::string &namespaceName = "");
@ -37,14 +37,14 @@ class create_controller : public DrObject<create_controller>, public CommandHand
void createWebsockController(std::vector<std::string> &ctlNames, const std::string &namespaceName = "");
void createWebsockController(const std::string &ctlName, const std::string &namespaceName = "");
void createApiController(std::vector<std::string> &apiClasses);
void createApiController(const std::string &className);
void createHttpController(std::vector<std::string> &httpClasses);
void createHttpController(const std::string &className);
void newSimpleControllerHeaderFile(std::ofstream &file, const std::string &ctlName, const std::string &namespaceName = "");
void newSimpleControllerSourceFile(std::ofstream &file, const std::string &ctlName, const std::string &namespaceName = "");
void newWebsockControllerHeaderFile(std::ofstream &file, const std::string &ctlName, const std::string &namespaceName = "");
void newWebsockControllerSourceFile(std::ofstream &file, const std::string &ctlName, const std::string &namespaceName = "");
void newApiControllerHeaderFile(std::ofstream &file, const std::string &className);
void newApiControllerSourceFile(std::ofstream &file, const std::string &className, const std::string &filename);
void newHttpControllerHeaderFile(std::ofstream &file, const std::string &className);
void newHttpControllerSourceFile(std::ofstream &file, const std::string &className, const std::string &filename);
};
} // namespace drogon_ctl

View File

@ -1,9 +1,9 @@
#pragma once
#include <drogon/HttpApiController.h>
#include <drogon/HttpController.h>
using namespace drogon;
namespace api
{
class Attachment : public drogon::HttpApiController<Attachment>
class Attachment : public drogon::HttpController<Attachment>
{
public:
METHOD_LIST_BEGIN

View File

@ -1,11 +1,11 @@
#pragma once
#include <drogon/HttpApiController.h>
#include <drogon/HttpController.h>
using namespace drogon;
namespace api
{
namespace v1
{
class ApiTest : public drogon::HttpApiController<ApiTest>
class ApiTest : public drogon::HttpController<ApiTest>
{
public:
METHOD_LIST_BEGIN

View File

@ -59,7 +59,7 @@ namespace api
{
namespace v1
{
class Test : public HttpApiController<Test>
class Test : public HttpController<Test>
{
public:
METHOD_LIST_BEGIN
@ -109,10 +109,10 @@ int main()
app().setThreadNum(4);
// trantor::Logger::setLogLevel(trantor::Logger::TRACE);
//class function
app().registerHttpApiMethod("/api/v1/handle1/{1}/{2}/?p3={3}&p4={4}", &A::handle);
app().registerHttpApiMethod("/api/v1/handle11/{1}/{2}/?p3={3}&p4={4}", &A::staticHandle);
app().registerHttpMethod("/api/v1/handle1/{1}/{2}/?p3={3}&p4={4}", &A::handle);
app().registerHttpMethod("/api/v1/handle11/{1}/{2}/?p3={3}&p4={4}", &A::staticHandle);
//lambda example
app().registerHttpApiMethod("/api/v1/handle2/{1}/{2}", [](const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int a, float b) {
app().registerHttpMethod("/api/v1/handle2/{1}/{2}", [](const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int a, float b) {
LOG_DEBUG << "int a=" << a;
LOG_DEBUG << "float b=" << b;
HttpViewData data;
@ -127,13 +127,13 @@ int main()
B b;
//functor example
app().registerHttpApiMethod("/api/v1/handle3/{1}/{2}", b);
app().registerHttpMethod("/api/v1/handle3/{1}/{2}", b);
A tmp;
std::function<void(const HttpRequestPtr &, const std::function<void(const HttpResponsePtr &)> &, int, const std::string &, const std::string &, int)>
func = std::bind(&A::handle, &tmp, _1, _2, _3, _4, _5, _6);
//api example for std::function
app().registerHttpApiMethod("/api/v1/handle4/{4}/{3}/{1}", func);
app().registerHttpMethod("/api/v1/handle4/{4}/{3}/{1}", func);
app().setDocumentRoot("./");
app().enableSession(60);

View File

@ -16,7 +16,7 @@
#include <drogon/config.h>
#include <drogon/utils/Utilities.h>
#include <drogon/HttpApiBinder.h>
#include <drogon/HttpBinder.h>
#include <trantor/utils/NonCopyable.h>
#include <drogon/DrObject.h>
#include <drogon/HttpRequest.h>
@ -77,15 +77,15 @@ class HttpAppFramework : public trantor::NonCopyable
const std::string &crtlName,
const std::vector<any> &filtersAndMethods = std::vector<any>()) = 0;
template <typename FUNCTION>
void registerHttpApiMethod(const std::string &pathPattern,
void registerHttpMethod(const std::string &pathPattern,
FUNCTION &&function,
const std::vector<any> &filtersAndMethods = std::vector<any>())
{
LOG_TRACE << "pathPattern:" << pathPattern;
HttpApiBinderBasePtr binder;
HttpBinderBasePtr binder;
binder = std::make_shared<
HttpApiBinder<FUNCTION>>(std::forward<FUNCTION>(function));
HttpBinder<FUNCTION>>(std::forward<FUNCTION>(function));
std::vector<HttpMethod> validMethods;
std::vector<std::string> filters;
@ -111,7 +111,7 @@ class HttpAppFramework : public trantor::NonCopyable
}
}
registerHttpApiController(pathPattern, binder, validMethods, filters);
registerHttpController(pathPattern, binder, validMethods, filters);
}
virtual void enableSession(const size_t timeout = 0) = 0;
virtual void disableSession() = 0;
@ -139,8 +139,8 @@ class HttpAppFramework : public trantor::NonCopyable
virtual void setIdleConnectionTimeout(size_t timeout) = 0;
private:
virtual void registerHttpApiController(const std::string &pathPattern,
const HttpApiBinderBasePtr &binder,
virtual void registerHttpController(const std::string &pathPattern,
const HttpBinderBasePtr &binder,
const std::vector<HttpMethod> &validMethods = std::vector<HttpMethod>(),
const std::vector<std::string> &filters = std::vector<std::string>()) = 0;
};

View File

@ -56,25 +56,25 @@ struct BinderArgTypeTraits<const T &>
static const bool isValid = true;
};
class HttpApiBinderBase
class HttpBinderBase
{
public:
virtual void handleHttpApiRequest(std::list<std::string> &pathParameter,
virtual void handleHttpRequest(std::list<std::string> &pathParameter,
const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> callback) = 0;
virtual size_t paramCount() = 0;
virtual ~HttpApiBinderBase() {}
virtual ~HttpBinderBase() {}
protected:
static std::map<std::string, std::shared_ptr<drogon::DrObjectBase>> _objMap;
static std::mutex _objMutex;
};
typedef std::shared_ptr<HttpApiBinderBase> HttpApiBinderBasePtr;
typedef std::shared_ptr<HttpBinderBase> HttpBinderBasePtr;
template <typename FUNCTION>
class HttpApiBinder : public HttpApiBinderBase
class HttpBinder : public HttpBinderBase
{
public:
typedef FUNCTION FunctionType;
virtual void handleHttpApiRequest(std::list<std::string> &pathParameter,
virtual void handleHttpRequest(std::list<std::string> &pathParameter,
const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> callback) override
{
run(pathParameter, req, callback);
@ -83,13 +83,13 @@ class HttpApiBinder : public HttpApiBinderBase
{
return traits::arity;
}
HttpApiBinder(FUNCTION &&func) : _func(std::forward<FUNCTION>(func))
HttpBinder(FUNCTION &&func) : _func(std::forward<FUNCTION>(func))
{
static_assert(traits::isHTTPApiFunction, "Your API handler function interface is wrong!");
static_assert(traits::isHTTPFunction, "Your API handler function interface is wrong!");
}
void test()
{
std::cout << "argument_count=" << argument_count << " " << traits::isHTTPApiFunction << std::endl;
std::cout << "argument_count=" << argument_count << " " << traits::isHTTPFunction << std::endl;
}
private:

View File

@ -39,7 +39,7 @@
namespace drogon
{
template <typename T>
class HttpApiController : public DrObject<T>
class HttpController : public DrObject<T>
{
protected:
template <typename FUNCTION>
@ -47,8 +47,8 @@ class HttpApiController : public DrObject<T>
const std::string &pattern,
const std::vector<any> &filtersAndMethods = std::vector<any>())
{
std::string path = std::string("/") + HttpApiController<T>::classTypeName();
LOG_TRACE << "classname:" << HttpApiController<T>::classTypeName();
std::string path = std::string("/") + HttpController<T>::classTypeName();
LOG_TRACE << "classname:" << HttpController<T>::classTypeName();
//transform(path.begin(), path.end(), path.begin(), tolower);
std::string::size_type pos;
@ -57,11 +57,11 @@ class HttpApiController : public DrObject<T>
path.replace(pos, 2, "/");
}
if (pattern.empty() || pattern[0] == '/')
app().registerHttpApiMethod(path + pattern,
app().registerHttpMethod(path + pattern,
std::forward<FUNCTION>(function),
filtersAndMethods);
else
app().registerHttpApiMethod(path + "/" + pattern,
app().registerHttpMethod(path + "/" + pattern,
std::forward<FUNCTION>(function),
filtersAndMethods);
}
@ -83,5 +83,5 @@ class HttpApiController : public DrObject<T>
}
};
template <typename T>
typename HttpApiController<T>::methodRegister HttpApiController<T>::_register;
typename HttpController<T>::methodRegister HttpController<T>::_register;
} // namespace drogon

View File

@ -22,7 +22,7 @@
#include <trantor/net/InetAddress.h>
#include <drogon/HttpAppFramework.h>
#include <drogon/HttpApiController.h>
#include <drogon/HttpController.h>
#include <drogon/HttpSimpleController.h>
#include <drogon/CacheMap.h>
#include <drogon/HttpClient.h>

View File

@ -76,7 +76,7 @@ template <
struct FunctionTraits<
ReturnType (*)(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, Arguments...)> : FunctionTraits<ReturnType (*)(Arguments...)>
{
static const bool isHTTPApiFunction = true;
static const bool isHTTPFunction = true;
};
//normal function
@ -95,7 +95,7 @@ struct FunctionTraits<
static const std::size_t arity = sizeof...(Arguments);
static const bool isHTTPApiFunction = false;
static const bool isHTTPFunction = false;
static const bool isClassFunction = false;
static const std::string name() { return std::string("Normal or Static Function"); }
};

View File

@ -42,8 +42,8 @@
using namespace drogon;
using namespace std::placeholders;
std::map<std::string, std::shared_ptr<drogon::DrObjectBase>> HttpApiBinderBase::_objMap;
std::mutex HttpApiBinderBase::_objMutex;
std::map<std::string, std::shared_ptr<drogon::DrObjectBase>> HttpBinderBase::_objMap;
std::mutex HttpBinderBase::_objMutex;
static void godaemon(void)
{
@ -108,7 +108,7 @@ void HttpAppFrameworkImpl::setFileTypes(const std::vector<std::string> &types)
void HttpAppFrameworkImpl::initRegex()
{
std::string regString;
for (auto &binder : _apiCtrlVector)
for (auto &binder : _ctrlVector)
{
std::regex reg("\\(\\[\\^/\\]\\*\\)");
std::string tmp = std::regex_replace(binder.pathParameterPattern, reg, "[^/]*");
@ -118,7 +118,7 @@ void HttpAppFrameworkImpl::initRegex()
if (regString.length() > 0)
regString.resize(regString.length() - 1); //remove the last '|'
LOG_TRACE << "regex string:" << regString;
_apiRegex = std::regex(regString, std::regex_constants::icase);
_ctrlRegex = std::regex(regString, std::regex_constants::icase);
}
void HttpAppFrameworkImpl::registerWebSocketController(const std::string &pathName,
const std::string &ctrlName,
@ -182,8 +182,8 @@ void HttpAppFrameworkImpl::registerHttpSimpleController(const std::string &pathN
}
}
}
void HttpAppFrameworkImpl::addApiPath(const std::string &path,
const HttpApiBinderBasePtr &binder,
void HttpAppFrameworkImpl::addHttpPath(const std::string &path,
const HttpBinderBasePtr &binder,
const std::vector<HttpMethod> &validMethods,
const std::vector<std::string> &filters)
{
@ -235,7 +235,7 @@ void HttpAppFrameworkImpl::addApiPath(const std::string &path,
paras = results.suffix();
}
}
struct ApiBinder _binder;
struct CtrlBinder _binder;
_binder.parameterPlaces = std::move(places);
_binder.queryParametersPlaces = std::move(parametersPlaces);
_binder.binderPtr = binder;
@ -250,12 +250,12 @@ void HttpAppFrameworkImpl::addApiPath(const std::string &path,
}
}
{
std::lock_guard<std::mutex> guard(_apiCtrlMutex);
_apiCtrlVector.push_back(std::move(_binder));
std::lock_guard<std::mutex> guard(_ctrlMutex);
_ctrlVector.push_back(std::move(_binder));
}
}
void HttpAppFrameworkImpl::registerHttpApiController(const std::string &pathPattern,
const HttpApiBinderBasePtr &binder,
void HttpAppFrameworkImpl::registerHttpController(const std::string &pathPattern,
const HttpBinderBasePtr &binder,
const std::vector<HttpMethod> &validMethods,
const std::vector<std::string> &filters)
{
@ -264,7 +264,7 @@ void HttpAppFrameworkImpl::registerHttpApiController(const std::string &pathPatt
std::string path(pathPattern);
//std::transform(path.begin(), path.end(), path.begin(), tolower);
addApiPath(path, binder, validMethods, filters);
addHttpPath(path, binder, validMethods, filters);
}
void HttpAppFrameworkImpl::setThreadNum(size_t threadNum)
{
@ -1012,22 +1012,22 @@ void HttpAppFrameworkImpl::onAsyncRequest(const HttpRequestPtr &req, const std::
});
return;
}
//find api controller
if (_apiRegex.mark_count() > 0)
//find http controller
if (_ctrlRegex.mark_count() > 0)
{
std::smatch result;
if (std::regex_match(req->path(), result, _apiRegex))
if (std::regex_match(req->path(), result, _ctrlRegex))
{
for (size_t i = 1; i < result.size(); i++)
{
//FIXME:Is there any better way to find the sub-match index without using loop?
if (!result[i].matched)
continue;
if (result[i].str() == req->path() && i <= _apiCtrlVector.size())
if (result[i].str() == req->path() && i <= _ctrlVector.size())
{
size_t ctlIndex = i - 1;
auto &binder = _apiCtrlVector[ctlIndex];
LOG_TRACE << "got api access,regex=" << binder.pathParameterPattern;
auto &binder = _ctrlVector[ctlIndex];
//LOG_TRACE << "got http access,regex=" << binder.pathParameterPattern;
if (binder._validMethodsFlags.size() > 0)
{
assert(binder._validMethodsFlags.size() > req->method());
@ -1042,7 +1042,7 @@ void HttpAppFrameworkImpl::onAsyncRequest(const HttpRequestPtr &req, const std::
}
auto &filters = binder.filtersName;
doFilters(filters, req, callback, needSetJsessionid, session_id, [=]() {
auto &binder = _apiCtrlVector[ctlIndex];
auto &binder = _ctrlVector[ctlIndex];
HttpResponsePtr responsePtr;
{
@ -1102,15 +1102,15 @@ void HttpAppFrameworkImpl::onAsyncRequest(const HttpRequestPtr &req, const std::
paraList.push_back(std::move(p));
}
binder.binderPtr->handleHttpApiRequest(paraList, req, [=](const HttpResponsePtr &resp) {
LOG_TRACE << "api resp:needSetJsessionid=" << needSetJsessionid << ";JSESSIONID=" << session_id;
binder.binderPtr->handleHttpRequest(paraList, req, [=](const HttpResponsePtr &resp) {
LOG_TRACE << "http resp:needSetJsessionid=" << needSetJsessionid << ";JSESSIONID=" << session_id;
auto newResp = resp;
if (resp->expiredTime() >= 0)
{
//cache the response;
std::dynamic_pointer_cast<HttpResponseImpl>(resp)->makeHeaderString();
{
auto &binderIterm = _apiCtrlVector[ctlIndex];
auto &binderIterm = _ctrlVector[ctlIndex];
std::lock_guard<std::mutex> guard(*(binderIterm.binderMtx));
_responseCacheMap->insert(binderIterm.pathParameterPattern, resp, resp->expiredTime());
binderIterm.responsePtr = resp;

View File

@ -87,8 +87,8 @@ class HttpAppFrameworkImpl : public HttpAppFramework
trantor::EventLoop *loop();
private:
virtual void registerHttpApiController(const std::string &pathPattern,
const HttpApiBinderBasePtr &binder,
virtual void registerHttpController(const std::string &pathPattern,
const HttpBinderBasePtr &binder,
const std::vector<HttpMethod> &validMethods = std::vector<HttpMethod>(),
const std::vector<std::string> &filters = std::vector<std::string>()) override;
@ -101,8 +101,8 @@ class HttpAppFrameworkImpl : public HttpAppFramework
void onWebsockDisconnect(const WebSocketConnectionPtr &wsConnPtr);
void onConnection(const TcpConnectionPtr &conn);
void readSendFile(const std::string &filePath, const HttpRequestPtr &req, const HttpResponsePtr &resp);
void addApiPath(const std::string &path,
const HttpApiBinderBasePtr &binder,
void addHttpPath(const std::string &path,
const HttpBinderBasePtr &binder,
const std::vector<HttpMethod> &validMethods,
const std::vector<std::string> &filters);
void initRegex();
@ -148,23 +148,22 @@ class HttpAppFrameworkImpl : public HttpAppFramework
std::unordered_map<std::string, WSCtrlAndFiltersName> _websockCtrlMap;
std::mutex _websockCtrlMutex;
struct ApiBinder
struct CtrlBinder
{
std::string pathParameterPattern;
std::vector<size_t> parameterPlaces;
std::map<std::string, size_t> queryParametersPlaces;
HttpApiBinderBasePtr binderPtr;
HttpBinderBasePtr binderPtr;
std::vector<std::string> filtersName;
std::unique_ptr<std::mutex> binderMtx = std::unique_ptr<std::mutex>(new std::mutex);
std::weak_ptr<HttpResponse> responsePtr;
std::vector<int> _validMethodsFlags;
std::regex _regex;
};
//std::unordered_map<std::string,ApiBinder>_apiCtrlMap;
std::vector<ApiBinder> _apiCtrlVector;
std::mutex _apiCtrlMutex;
std::vector<CtrlBinder> _ctrlVector;
std::mutex _ctrlMutex;
std::regex _apiRegex;
std::regex _ctrlRegex;
bool _enableLastModify = true;
std::set<std::string> _fileTypeSet = {"html", "js", "css", "xml", "xsl", "txt", "svg", "ttf",
"otf", "woff2", "woff", "eot", "png", "jpg", "jpeg",