50 lines
1.6 KiB
C++
50 lines
1.6 KiB
C++
#pragma once
|
|
|
|
#include "Route.h"
|
|
|
|
#include <functional>
|
|
#include <vector>
|
|
|
|
namespace VWeb {
|
|
typedef std::function<bool(Request &, Response &)> RouteFunction;
|
|
typedef std::function<std::shared_ptr<Route>()> RouteInstaniateFunction;
|
|
|
|
class Router {
|
|
public:
|
|
Router();
|
|
void DeleteRoute(const std::string &name);
|
|
|
|
Ref<Response> HandleRoute(Ref<Request> &request);
|
|
Ref<Route> FindRoute(Ref<Request> &request);
|
|
static void AddToArgs(Ref<Request> &request, std::vector<std::string> &items);
|
|
|
|
template <typename T>
|
|
void Register(const std::string &endpoint, HttpMethod allowedMethod) {
|
|
Register<T>(endpoint, static_cast<uint32_t>(allowedMethod));
|
|
}
|
|
|
|
template <typename T>
|
|
void
|
|
Register(const std::string &endpoint,
|
|
uint32_t allowedMethods = static_cast<uint32_t>(HttpMethod::ALL)) {
|
|
static_assert(std::is_base_of_v<Route, T>, "must be a Route");
|
|
allowedMethods |= HttpMethod::HEAD | HttpMethod::OPTIONS;
|
|
m_Routes[endpoint] = {.AllowedMethods = allowedMethods,
|
|
.Instaniate = [] { return std::make_shared<T>(); }};
|
|
}
|
|
|
|
void Get(const std::string &path, RouteFunction);
|
|
void Post(const std::string &path, RouteFunction);
|
|
void Put(const std::string &path, RouteFunction);
|
|
void Patch(const std::string &path, RouteFunction);
|
|
void Delete(const std::string &path, RouteFunction);
|
|
|
|
private:
|
|
struct RouteInstance {
|
|
uint32_t AllowedMethods = HttpMethod::OPTIONS | HttpMethod::HEAD;
|
|
RouteInstaniateFunction Instaniate;
|
|
};
|
|
std::unordered_map<std::string, RouteInstance> m_Routes;
|
|
std::unordered_map<std::string, RouteFunction> m_FunctionRoutes;
|
|
};
|
|
} // namespace VWeb
|