Closed hwc0919 closed 1 month ago
class MyMiddleware : public HttpMiddleware<MyMiddleware> { public: MyMiddleware(){}; // do not omit constructor void invoke(const HttpRequestPtr &req, MiddlewareNextCallback &&nextCb, MiddlewareCallback &&mcb) override { if (req->path() == "/some/path") { // intercept directly mcb(HttpResponse::newNotFoundResponse(req)); return; } // Do something before calling the next middleware nextCb([mcb = std::move(mcb)](const HttpResponsePtr &resp) { // Do something after the next middleware returns mcb(resp); }); } }; class MyCoroMiddleware : public HttpCoroMiddleware<MyCoroMiddleware> { public: MyCoroMiddleware(){}; // do not omit constructor Task<HttpResponsePtr> invoke( const HttpRequestPtr &req, MiddlewareNextAwaiter &&nextAwaiter) override { if (req->path() == "/some/path") { // intercept directly co_return HttpResponse::newNotFoundResponse(req); } // Do something before calling the next middleware auto resp = co_await nextAwaiter; // Do something after the next middleware returns co_return resp; } }; class MiddlewareTest : public drogon::HttpController<MiddlewareTest> { public: METHOD_LIST_BEGIN ADD_METHOD_TO(MiddlewareTest::handleRequest, "/test-middleware", Get, "MyFilter", "MyMiddleware", "MyCoroMiddleware"); METHOD_LIST_END void handleRequest( const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback) const { callback(HttpResponse::newHttpResponse()); } };
@an-tao I have midterms next week, my review may take a while
Example codes