drogonframework / drogon

Drogon: A C++14/17/20 based HTTP web application framework running on Linux/macOS/Unix/Windows
MIT License
11.04k stars 1.06k forks source link

Support per-method middlewares. #2015

Closed hwc0919 closed 1 month ago

hwc0919 commented 2 months ago

Example codes


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());
    }
};
Mis1eader-dev commented 2 months ago

@an-tao I have midterms next week, my review may take a while