Add registerMiddleware (#2052)

This commit is contained in:
fantasy-peak 2024-06-04 17:05:52 +08:00 committed by GitHub
parent 9a96a20c6e
commit 0a889e921d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 49 additions and 2 deletions

View File

@ -691,6 +691,24 @@ class DROGON_EXPORT HttpAppFramework : public trantor::NonCopyable
return *this;
}
/// Register middleware objects created and initialized by the user
/**
* This method is similar to the above method.
*/
template <typename T>
HttpAppFramework &registerMiddleware(
const std::shared_ptr<T> &middlewarePtr)
{
static_assert(std::is_base_of<HttpMiddlewareBase, T>::value,
"Error! Only middleware objects can be registered here");
static_assert(!T::isAutoCreation,
"Middleware created and initialized "
"automatically by drogon cannot be "
"registered here");
DrClassMap::setSingleInstance(middlewarePtr);
return *this;
}
/// 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

View File

@ -1053,7 +1053,7 @@ void doTest(const HttpClientPtr &client, std::shared_ptr<test::Case> TEST_CTX)
[TEST_CTX, req](ReqResult r,
const HttpResponsePtr &resp) {
REQUIRE(r == ReqResult::Ok);
CHECK(resp->body() == "123test321");
CHECK(resp->body() == "1234test4321");
});
req = HttpRequest::newHttpRequest();

View File

@ -132,7 +132,8 @@ class MiddlewareTest : public drogon::HttpController<MiddlewareTest>
Get,
"Middleware1",
"Middleware2",
"Middleware3");
"Middleware3",
"Middleware4");
ADD_METHOD_TO(MiddlewareTest::handleRequest,
"/test-middleware-block",
Get,

View File

@ -154,6 +154,30 @@ std::string_view fromRequest(const HttpRequest &req)
}
} // namespace drogon
class Middleware4 : public drogon::HttpMiddleware<Middleware4, false>
{
public:
Middleware4()
{
LOG_DEBUG << "Middleware4\n";
};
void invoke(const HttpRequestPtr &req,
MiddlewareNextCallback &&nextCb,
MiddlewareCallback &&mcb) override
{
auto ptr = req->attributes()->get<std::shared_ptr<std::string>>(
"test-middleware");
ptr->append("4");
nextCb([req, ptr, mcb = std::move(mcb)](const HttpResponsePtr &resp) {
ptr->append("4");
resp->setBody(*ptr);
mcb(resp);
});
}
};
/// Some examples in the main function show some common functions of drogon. In
/// practice, we don't need such a lengthy main function.
int main()
@ -268,6 +292,10 @@ int main()
app().registerFilter(filterPtr);
app().setIdleConnectionTimeout(30s);
// Install custom Middleware
auto middlewarePtr = std::make_shared<Middleware4>();
app().registerMiddleware(middlewarePtr);
// AOP example
app().registerBeginningAdvice(
[]() { LOG_DEBUG << "Event loop is running!"; });