Add blueprint middleware example

This commit is contained in:
Vladislav Oleshko 2022-05-07 23:24:42 +03:00
parent 4d4d0094fe
commit d259999e6d

View File

@ -5,11 +5,13 @@ struct RequestLogger
struct context
{};
// This method is run before handling the request
void before_handle(crow::request& req, crow::response& /*res*/, context& /*ctx*/)
{
CROW_LOG_INFO << "Request to:" + req.url;
}
// This method is run after handling the request
void after_handle(crow::request& /*req*/, crow::response& /*res*/, context& /*ctx*/)
{}
};
@ -23,6 +25,7 @@ struct SecretContentGuard : crow::ILocalMiddleware
void before_handle(crow::request& /*req*/, crow::response& res, context& /*ctx*/)
{
// A request can be aborted prematurely
res.write("SECRET!");
res.code = 403;
res.end();
@ -32,10 +35,28 @@ struct SecretContentGuard : crow::ILocalMiddleware
{}
};
struct RequestAppend : crow::ILocalMiddleware
{
// Values from this context can be accessed from handlers
struct context
{
std::string message;
};
void before_handle(crow::request& /*req*/, crow::response& /*res*/, context& /*ctx*/)
{}
void after_handle(crow::request& /*req*/, crow::response& res, context& ctx)
{
// The response can be modified
res.write(" + (" + ctx.message + ")");
}
};
int main()
{
// ALL middleware (including per handler) is listed
crow::App<RequestLogger, SecretContentGuard> app;
crow::App<RequestLogger, SecretContentGuard, RequestAppend> app;
CROW_ROUTE(app, "/")
([]() {
@ -48,7 +69,20 @@ int main()
return "";
});
app.port(18080).run();
crow::Blueprint bp("bp", "c", "c");
// Register middleware on all routes on a specific blueprint
// This also applies to sub blueprints
bp.CROW_MIDDLEWARES(app, RequestAppend);
CROW_BP_ROUTE(bp, "/")
([&](const crow::request& req) {
// Get RequestAppends context
auto& ctx = app.get_context<RequestAppend>(req);
ctx.message = "World";
return "Hello:";
});
app.register_blueprint(bp);
app.port(18080).run();
return 0;
}