68 lines
1.8 KiB
C++
68 lines
1.8 KiB
C++
#pragma once
|
|||
|
|
|
||
|
|
// Application: composition root. Owns routers, middleware chain, sub-app
|
||
|
|
// mounts, and the typed error mapping. Gap: real molo::app::Application in
|
||
|
|
// 05-request-routing.md owns lifespan hooks, plugin registry, and the full DI
|
||
|
|
// container; this skeleton passes a Services struct to route factories.
|
||
|
|
|
||
|
|
#include <functional>
|
||
|
|
#include <memory>
|
||
|
|
#include <string>
|
||
|
|
#include <vector>
|
||
|
|
|
||
|
|
#include "Http.hpp"
|
||
|
|
#include "Router.hpp"
|
||
|
|
|
||
|
|
namespace molo::example::fw {
|
||
|
|
|
||
|
|
enum class MiddlewareSlot {
|
||
|
|
Errors = 0,
|
||
|
|
Observability = 1,
|
||
|
|
Security = 2,
|
||
|
|
SessionAuth = 3,
|
||
|
|
User = 4,
|
||
|
|
};
|
||
|
|
|
||
|
|
using Next = std::function<Response(Request)>;
|
||
|
|
using Middleware = std::function<Response(Request, Next)>;
|
||
|
|
|
||
|
|
class HttpError {
|
||
|
|
public:
|
||
|
|
HttpError(int status, std::string code, std::string message);
|
||
|
|
int status() const;
|
||
|
|
const std::string& code() const;
|
||
|
|
const std::string& message() const;
|
||
|
|
|
||
|
|
private:
|
||
|
|
int status_;
|
||
|
|
std::string code_;
|
||
|
|
std::string message_;
|
||
|
|
};
|
||
|
|
|
||
|
|
class Application : public std::enable_shared_from_this<Application> {
|
||
|
|
public:
|
||
|
|
void use(MiddlewareSlot slot, Middleware middleware);
|
||
|
|
void include_router(const std::string& prefix, const Router& router,
|
||
|
|
const std::string& name_prefix = "");
|
||
|
|
void mount(const std::string& path, std::shared_ptr<Application> sub);
|
||
|
|
|
||
|
|
Response dispatch(Request req);
|
||
|
|
|
||
|
|
const std::vector<Route>& routes() const;
|
||
|
|
|
||
|
|
private:
|
||
|
|
Response dispatch_inner(Request req, int depth);
|
||
|
|
Response run_chain(Request req, int depth);
|
||
|
|
|
||
|
|
Router router_;
|
||
|
|
std::vector<std::pair<MiddlewareSlot, Middleware>> middlewares_;
|
||
|
|
std::vector<std::pair<std::string, std::shared_ptr<Application>>> mounts_;
|
||
|
|
MiddlewareSlot last_slot_ = MiddlewareSlot::Errors;
|
||
|
|
bool has_middleware_ = false;
|
||
|
|
};
|
||
|
|
|
||
|
|
Middleware errors_middleware();
|
||
|
|
Middleware request_id_middleware();
|
||
|
|
|
||
|
|
} // namespace molo::example::fw
|