Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
Router.hpp
Go to the documentation of this file.
1#pragma once
8#include <functional>
9#include <exception>
10#include <unordered_map>
11#include <unordered_set>
12#include <vector>
13#include <string>
14#include <memory>
15
16namespace orbit::routing {
17
18using RouteHandler = std::function<void(http::HttpRequest&, std::shared_ptr<http::ResponseWriter>)>;
19using Middleware = std::function<bool(http::HttpRequest&, std::shared_ptr<http::ResponseWriter>)>;
20using WsHandler = std::function<void(http::websocket::WebSocketConnection&)>;
21using ErrorHandler = std::function<void(const std::exception&, http::HttpRequest&, std::shared_ptr<http::ResponseWriter>)>;
22
23struct WsRoute {
25 std::vector<Middleware> middlewares; // Group and route middleware, outermost first
26};
27
31struct ErrorScope {
33 std::shared_ptr<const ErrorScope> parent;
34};
35
38 std::vector<std::string> path_segments;
40 std::shared_ptr<const ErrorScope> errors; // null: the app's handler
41};
42
46class Router {
47public:
53 Router(const std::string& prefix = "", Router* parent = nullptr)
54 : prefix_(prefix), parent_(parent),
55 openapi_(parent ? parent->openapi_ : std::make_shared<openapi::OpenApiRegistry>()) {}
56
59
64 public:
65 RouteBuilder(Router& router, http::HttpMethod method, const std::string& path, std::vector<Middleware> mws = {})
66 : router_(router), method_(method), path_(path), mws_(std::move(mws)) {}
67
68 RouteBuilder& summary(const std::string& s) { meta_.summary = s; return *this; }
69 RouteBuilder& description(const std::string& s) { meta_.description = s; return *this; }
70 RouteBuilder& tag(const std::string& t) { meta_.tags.push_back(t); return *this; }
71 RouteBuilder& req_body(const std::string& schema_name) { meta_.request_body_schema = schema_name; return *this; }
72 RouteBuilder& res_body(int status, const std::string& schema_name) { meta_.response_schemas[status] = schema_name; return *this; }
73
75 private:
78 std::string path_;
79 std::vector<Middleware> mws_;
81 };
82
95 RouteBuilder route(const std::string& path, http::HttpMethod method = http::HttpMethod::GET) {
96 return RouteBuilder(*this, method, path);
97 }
98
99 // Route Grouping
105 void group(const std::string& prefix, std::function<void(Router&)> callback);
106
107 // Register a handler for a specific HTTP method and path
108 void add_route(http::HttpMethod method, const std::string& path, RouteHandler handler);
109 void add_route(http::HttpMethod method, const std::string& path, std::vector<Middleware> mws, RouteHandler handler);
110 void add_route_with_meta(http::HttpMethod method, const std::string& path, std::vector<Middleware> mws, const openapi::RouteMetadata& meta, RouteHandler handler);
111
112 // Fluent routing API
113 Router& get(const std::string& path, RouteHandler handler);
114 Router& get(const std::string& path, std::vector<Middleware> mws, RouteHandler handler);
115
116 Router& post(const std::string& path, RouteHandler handler);
117 Router& post(const std::string& path, std::vector<Middleware> mws, RouteHandler handler);
118
119 Router& put(const std::string& path, RouteHandler handler);
120 Router& put(const std::string& path, std::vector<Middleware> mws, RouteHandler handler);
121
122 Router& patch(const std::string& path, RouteHandler handler);
123 Router& patch(const std::string& path, std::vector<Middleware> mws, RouteHandler handler);
124
125 Router& del(const std::string& path, RouteHandler handler);
126 Router& del(const std::string& path, std::vector<Middleware> mws, RouteHandler handler);
127
128 Router& options(const std::string& path, RouteHandler handler);
129 Router& options(const std::string& path, std::vector<Middleware> mws, RouteHandler handler);
130
131 void ws(const std::string& path, WsHandler handler);
132 void ws(const std::string& path, std::vector<Middleware> mws, WsHandler handler);
133
139 bool run_ws_middlewares(const std::string& path, http::HttpRequest& request, std::shared_ptr<http::ResponseWriter> response_writer) const;
141
150 void use(const std::string& prefix, Middleware m);
151
154 void not_found(RouteHandler handler);
155
160 void on_error(ErrorHandler handler);
161
162 // Route an incoming request to the correct handler
163 void route(http::HttpRequest& request, std::shared_ptr<http::ResponseWriter> response_writer) const;
164
165 bool has_ws_route(const std::string& path) const;
166
179 std::vector<std::string> validate_routes() const;
180
181private:
182 // Error handling for an exception from a route, middleware or (later,
183 // through the writer's error sink) an asynchronous handler.
184 void handle_exception(std::exception_ptr error, http::HttpRequest& request,
185 std::shared_ptr<http::ResponseWriter> response_writer,
186 const ErrorScope* scope = nullptr) const;
187
188 struct StaticRoute {
190 std::shared_ptr<const ErrorScope> errors; // null: the app's handler
191 };
192
193public:
194 WsHandler get_ws_route(const std::string& path) const;
195
196 // Check if a given path is registered as a streaming route
197 bool is_stream_route(http::HttpMethod method, const std::string& path) const;
198 void add_stream_route(http::HttpMethod method, const std::string& path, RouteHandler handler);
199
200private:
201
202 std::string make_route_key(http::HttpMethod method, std::string_view path) const;
203 void mark_stream_route(http::HttpMethod method, const std::string& full_path);
204 std::vector<std::string> split_path(std::string_view path) const;
205
206 // Matches request segments against a route pattern of literal, ":param",
207 // "{param}" / "{param:type}" (typed; see segment_matches_type) and a
208 // trailing "*" / "*name" segment. Fills @p params and returns the number
209 // of literal segments matched, or -1 for no match (including a typed
210 // segment whose value does not fit its type).
211 static int match_segments(const std::vector<std::string>& pattern, const std::vector<std::string>& request,
212 std::unordered_map<std::string, std::string>* params);
213 static bool is_wildcard(const std::string& segment) { return !segment.empty() && segment[0] == '*'; }
214 Router* root() { return parent_ ? parent_ : this; }
215 const Router* root() const { return parent_ ? parent_ : this; }
216
217 std::string prefix_;
218 Router* parent_{nullptr};
219 std::shared_ptr<openapi::OpenApiRegistry> openapi_;
220 std::vector<Middleware> local_middlewares_;
222 std::shared_ptr<ErrorScope> error_scope_; // groups only
224
225 std::unordered_map<std::string, StaticRoute> routes_;
226 std::unordered_map<std::string, WsRoute> ws_routes_;
227 std::vector<DynamicRoute> dynamic_routes_;
228 std::vector<Middleware> middlewares_;
229
230 std::unordered_set<std::string> stream_routes_;
231 std::vector<DynamicRoute> dynamic_stream_routes_;
232
233 // Registrations per "METHOD full-pattern-text" key (root router only;
234 // see root()), for validate_routes().
235 std::unordered_map<std::string, int> registration_counts_;
236};
237
238} // namespace routing
Represents an active WebSocket connection.
Definition WebSocketConnection.hpp:88
Definition OpenApi.hpp:20
A builder class for fluent route configuration.
Definition Router.hpp:63
std::string path_
Definition Router.hpp:78
RouteBuilder & tag(const std::string &t)
Definition Router.hpp:70
std::vector< Middleware > mws_
Definition Router.hpp:79
RouteBuilder & res_body(int status, const std::string &schema_name)
Definition Router.hpp:72
RouteBuilder & summary(const std::string &s)
Definition Router.hpp:68
Router & router_
Definition Router.hpp:76
http::HttpMethod method_
Definition Router.hpp:77
RouteBuilder & req_body(const std::string &schema_name)
Definition Router.hpp:71
RouteBuilder(Router &router, http::HttpMethod method, const std::string &path, std::vector< Middleware > mws={})
Definition Router.hpp:65
openapi::RouteMetadata meta_
Definition Router.hpp:80
RouteBuilder & description(const std::string &s)
Definition Router.hpp:69
Manages routing of HTTP requests to their appropriate handlers.
Definition Router.hpp:46
std::unordered_map< std::string, WsRoute > ws_routes_
Definition Router.hpp:226
ErrorHandler error_handler_
Definition Router.hpp:221
void use(const std::string &prefix, Middleware m)
Runs m only for requests under prefix: the prefix itself and anything below it ("/svc" and "/svc/....
Router & post(const std::string &path, RouteHandler handler)
Router(const std::string &prefix="", Router *parent=nullptr)
Constructs a new Router.
Definition Router.hpp:53
openapi::OpenApiRegistry & openapi()
The OpenAPI registry for this router tree (shared by its groups).
Definition Router.hpp:58
std::shared_ptr< ErrorScope > error_scope_
Definition Router.hpp:222
std::unordered_map< std::string, int > registration_counts_
Definition Router.hpp:235
std::string prefix_
Definition Router.hpp:217
Router * parent_
Definition Router.hpp:218
Router * root()
Definition Router.hpp:214
std::vector< DynamicRoute > dynamic_routes_
Definition Router.hpp:227
std::shared_ptr< openapi::OpenApiRegistry > openapi_
Definition Router.hpp:219
void add_route(http::HttpMethod method, const std::string &path, RouteHandler handler)
void add_route_with_meta(http::HttpMethod method, const std::string &path, std::vector< Middleware > mws, const openapi::RouteMetadata &meta, RouteHandler handler)
void on_error(ErrorHandler handler)
std::vector< Middleware > middlewares_
Definition Router.hpp:228
std::vector< Middleware > local_middlewares_
Definition Router.hpp:220
void not_found(RouteHandler handler)
void add_route(http::HttpMethod method, const std::string &path, std::vector< Middleware > mws, RouteHandler handler)
Router & patch(const std::string &path, std::vector< Middleware > mws, RouteHandler handler)
RouteHandler not_found_handler_
Definition Router.hpp:223
void handle_exception(std::exception_ptr error, http::HttpRequest &request, std::shared_ptr< http::ResponseWriter > response_writer, const ErrorScope *scope=nullptr) const
void add_stream_route(http::HttpMethod method, const std::string &path, RouteHandler handler)
WsHandler get_ws_route(const std::string &path) const
std::unordered_set< std::string > stream_routes_
Definition Router.hpp:230
std::vector< std::string > validate_routes() const
Finds routes registered more than once: the same HTTP method and exact path pattern (text,...
std::string make_route_key(http::HttpMethod method, std::string_view path) const
Router & get(const std::string &path, std::vector< Middleware > mws, RouteHandler handler)
Router & options(const std::string &path, RouteHandler handler)
bool is_stream_route(http::HttpMethod method, const std::string &path) const
void use(Middleware m)
void ws(const std::string &path, WsHandler handler)
void group(const std::string &prefix, std::function< void(Router &)> callback)
Creates a route group with a specific prefix.
Router & put(const std::string &path, std::vector< Middleware > mws, RouteHandler handler)
std::vector< DynamicRoute > dynamic_stream_routes_
Definition Router.hpp:231
Router & get(const std::string &path, RouteHandler handler)
Router & put(const std::string &path, RouteHandler handler)
static int match_segments(const std::vector< std::string > &pattern, const std::vector< std::string > &request, std::unordered_map< std::string, std::string > *params)
std::unordered_map< std::string, StaticRoute > routes_
Definition Router.hpp:225
Router & del(const std::string &path, RouteHandler handler)
const Router * root() const
Definition Router.hpp:215
bool run_ws_middlewares(const std::string &path, http::HttpRequest &request, std::shared_ptr< http::ResponseWriter > response_writer) const
Runs global, group and route middleware for a WebSocket upgrade.
void ws(const std::string &path, std::vector< Middleware > mws, WsHandler handler)
std::vector< std::string > split_path(std::string_view path) const
RouteBuilder route(const std::string &path, http::HttpMethod method=http::HttpMethod::GET)
Initiates a route builder for a specific path and method.
Definition Router.hpp:95
static bool is_wildcard(const std::string &segment)
Definition Router.hpp:213
Router & options(const std::string &path, std::vector< Middleware > mws, RouteHandler handler)
bool has_ws_route(const std::string &path) const
void mark_stream_route(http::HttpMethod method, const std::string &full_path)
Router & del(const std::string &path, std::vector< Middleware > mws, RouteHandler handler)
Router & post(const std::string &path, std::vector< Middleware > mws, RouteHandler handler)
Router & patch(const std::string &path, RouteHandler handler)
void route(http::HttpRequest &request, std::shared_ptr< http::ResponseWriter > response_writer) const
HttpMethod
Represents standard HTTP methods.
Definition HttpRequest.hpp:28
Definition legacy_namespaces.hpp:22
Definition legacy_namespaces.hpp:24
std::function< void(http::websocket::WebSocketConnection &)> WsHandler
Definition Router.hpp:20
std::function< bool(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> Middleware
Definition Router.hpp:19
std::function< void(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> RouteHandler
Definition Router.hpp:18
std::function< void(const std::exception &, http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> ErrorHandler
Definition Router.hpp:21
Definition json.hpp:5363
Represents an incoming HTTP request.
Definition HttpRequest.hpp:54
Definition OpenApi.hpp:12
std::unordered_map< int, std::string > response_schemas
Definition OpenApi.hpp:17
std::string summary
Definition OpenApi.hpp:13
std::string request_body_schema
Definition OpenApi.hpp:16
std::vector< std::string > tags
Definition OpenApi.hpp:15
std::string description
Definition OpenApi.hpp:14
Definition Router.hpp:36
std::vector< std::string > path_segments
Definition Router.hpp:38
http::HttpMethod method
Definition Router.hpp:37
RouteHandler handler
Definition Router.hpp:39
std::shared_ptr< const ErrorScope > errors
Definition Router.hpp:40
Definition Router.hpp:31
ErrorHandler handler
Definition Router.hpp:32
std::shared_ptr< const ErrorScope > parent
Definition Router.hpp:33
Definition Router.hpp:188
std::shared_ptr< const ErrorScope > errors
Definition Router.hpp:190
RouteHandler handler
Definition Router.hpp:189
Definition Router.hpp:23
std::vector< Middleware > middlewares
Definition Router.hpp:25
WsHandler handler
Definition Router.hpp:24