libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
httprouter.h
Go to the documentation of this file.
1
8#pragma once
9
10
11#include <promeki/config.h>
12#if PROMEKI_ENABLE_HTTP
13#include <promeki/namespace.h>
14#include <promeki/string.h>
15#include <promeki/list.h>
16#include <promeki/hashmap.h>
17#include <promeki/httpmethod.h>
18#include <promeki/httprequest.h>
20#include <promeki/httphandler.h>
21
22PROMEKI_NAMESPACE_BEGIN
23
78class HttpRouter {
79 public:
81 HttpRouter();
82
84 ~HttpRouter();
85
94 void route(const String &pattern, const HttpMethod &method, HttpHandlerFunc handler);
95
102 void route(const String &pattern, const HttpMethod &method, HttpHandler::Ptr handler);
103
111 void any(const String &pattern, HttpHandlerFunc handler);
113 void any(const String &pattern, HttpHandler::Ptr handler);
114
121 void use(HttpMiddleware middleware);
122
128 void setNotFoundHandler(HttpHandlerFunc handler);
129
138 void setMethodNotAllowedHandler(HttpHandlerFunc handler);
139
148 void dispatch(HttpRequest &request, HttpResponse &response) const;
149
151 int routeCount() const;
152
154 bool hasRoutes() const { return routeCount() > 0; }
155
157 void clear();
158
159 private:
160 struct PatternSegment {
161 using List = ::promeki::List<PatternSegment>;
162 enum Kind {
163 Literal,
164 Param,
165 Greedy
166 };
167 Kind kind = Literal;
168 String text;
169 };
170
171 struct Pattern {
172 using List = ::promeki::List<Pattern>;
173 String source;
174 PatternSegment::List segments;
175 bool trailingSlash = false;
176 bool isExact = true;
177 };
178
179 struct Route {
180 using List = ::promeki::List<Route>;
181 Pattern pattern;
182 int methodValue = -1;
183 HttpHandler::Ptr handler;
184 };
185
186 static Pattern compilePattern(const String &source);
187 static bool matchPattern(const Pattern &pattern, const String &path,
188 HashMap<String, String> &paramsOut);
189 static int patternScore(const Pattern &pattern);
190
191 void runChain(HttpRequest &request, HttpResponse &response, HttpHandlerFunc terminal) const;
192
193 static void defaultNotFound(const HttpRequest &request, HttpResponse &response);
194 static void defaultMethodNotAllowed(const HttpRequest &request, HttpResponse &response);
195
196 Route::List _routes;
197 HttpMiddlewareList _middleware;
198 HttpHandlerFunc _notFound;
199 HttpHandlerFunc _methodNotAllowed;
200};
201
202PROMEKI_NAMESPACE_END
203
204#endif // PROMEKI_ENABLE_HTTP