Crow/examples/example_middleware.cpp

89 lines
2.2 KiB
C++
Raw Normal View History

2022-02-01 13:31:05 +00:00
#include "crow.h"
struct RequestLogger
{
struct context
{};
2022-05-07 20:24:42 +00:00
// This method is run before handling the request
2022-02-01 13:31:05 +00:00
void before_handle(crow::request& req, crow::response& /*res*/, context& /*ctx*/)
{
CROW_LOG_INFO << "Request to:" + req.url;
}
2022-05-07 20:24:42 +00:00
// This method is run after handling the request
2022-02-01 13:31:05 +00:00
void after_handle(crow::request& /*req*/, crow::response& /*res*/, context& /*ctx*/)
{}
};
// Per handler middleware has to extend ILocalMiddleware
// It is called only if enabled
struct SecretContentGuard : crow::ILocalMiddleware
{
struct context
{};
void before_handle(crow::request& /*req*/, crow::response& res, context& /*ctx*/)
{
2022-05-07 20:24:42 +00:00
// A request can be aborted prematurely
2022-02-01 13:31:05 +00:00
res.write("SECRET!");
res.code = 403;
res.end();
}
void after_handle(crow::request& /*req*/, crow::response& /*res*/, context& /*ctx*/)
{}
};
2022-05-07 20:24:42 +00:00
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 + ")");
}
};
2022-02-01 13:31:05 +00:00
int main()
{
// ALL middleware (including per handler) is listed
2022-05-07 20:24:42 +00:00
crow::App<RequestLogger, SecretContentGuard, RequestAppend> app;
2022-02-01 13:31:05 +00:00
CROW_ROUTE(app, "/")
([]() {
return "Hello, world!";
});
CROW_ROUTE(app, "/secret")
2022-02-01 20:21:07 +00:00
// Enable SecretContentGuard for this handler
2022-02-08 17:11:02 +00:00
.CROW_MIDDLEWARES(app, SecretContentGuard)([]() {
2022-02-01 20:21:07 +00:00
return "";
});
2022-02-01 13:31:05 +00:00
2022-05-07 20:24:42 +00:00
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);
2022-02-01 13:31:05 +00:00
2022-05-07 20:24:42 +00:00
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();
2022-02-01 13:31:05 +00:00
return 0;
}