Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
HandlerWrapper.hpp
Go to the documentation of this file.
1#pragma once
6#include <orbit/http/json.hpp>
7#include <type_traits>
8#include <functional>
9#include <memory>
10#include <string>
11#include <tuple>
12
13namespace orbit::routing {
14
15// Function traits to inspect lambda signatures
16template <typename T>
17struct function_traits : public function_traits<decltype(&std::decay_t<T>::operator())> {};
18
19// Specialization for const lambdas
20template <typename ClassType, typename ReturnType, typename... Args>
21struct function_traits<ReturnType(ClassType::*)(Args...) const> {
22 using result_type = ReturnType;
23 using args_tuple = std::tuple<Args...>;
24 static constexpr size_t arg_count = sizeof...(Args);
25};
26
27// Specialization for mutable lambdas
28template <typename ClassType, typename ReturnType, typename... Args>
29struct function_traits<ReturnType(ClassType::*)(Args...)> {
30 using result_type = ReturnType;
31 using args_tuple = std::tuple<Args...>;
32 static constexpr size_t arg_count = sizeof...(Args);
33};
34
35// Specialization for free functions
36template <typename ReturnType, typename... Args>
37struct function_traits<ReturnType(*)(Args...)> {
38 using result_type = ReturnType;
39 using args_tuple = std::tuple<Args...>;
40 static constexpr size_t arg_count = sizeof...(Args);
41};
42
43// The core wrapper
44template <typename Handler>
45auto wrap_handler(Handler&& h) -> std::function<void(http::HttpRequest&, std::shared_ptr<http::ResponseWriter>)> {
46 using traits = function_traits<Handler>;
47 using Ret = typename traits::result_type;
48
49 if constexpr (std::is_same_v<Ret, void> || traits::arg_count == 2) {
50 // It's a standard handler or a Coroutine Task handling its own ResponseWriter. We just pass it through.
51 // Assumes signature: (HttpRequest&, shared_ptr<ResponseWriter>)
52 return [h = std::forward<Handler>(h)](http::HttpRequest& req, std::shared_ptr<http::ResponseWriter> writer) mutable {
53 h(req, writer);
54 };
55 } else {
56 // It returns a value! Let's auto-serialize it.
57 return [h = std::forward<Handler>(h)](http::HttpRequest& req, std::shared_ptr<http::ResponseWriter> writer) mutable {
58 try {
59 Ret result;
60 if constexpr (traits::arg_count == 0) {
61 result = h();
62 } else if constexpr (traits::arg_count == 1) {
63 result = h(req);
64 } else {
65 static_assert(traits::arg_count <= 1, "Magic handlers can only take 0 or 1 arguments (HttpRequest&)");
66 }
67
69 if constexpr (std::is_same_v<Ret, std::string>) {
70 res.status(http::HttpStatus::OK).send(result);
71 res.headers["Content-Type"] = "text/plain";
72 } else if constexpr (std::is_same_v<Ret, nlohmann::json>) {
73 res.status(http::HttpStatus::OK).send(result.dump());
74 res.headers["Content-Type"] = "application/json";
75 } else {
76 // It must be a C++ struct. nlohmann::json will serialize it!
77 nlohmann::json j = result;
79 res.headers["Content-Type"] = "application/json";
80 }
81 writer->send(std::move(res));
82 } catch (...) {
83 // Let Router::route handle it: it logs the details, runs the
84 // application's on_error handler, and never sends the
85 // exception text to the client.
86 throw;
87 }
88 };
89 }
90}
91
92} // namespace routing
a class to store JSON values
Definition json.hpp:19401
string_t dump(const int indent=-1, const char indent_char=' ', const bool ensure_ascii=false, const error_handler_t error_handler=error_handler_t::strict) const
serialization
Definition json.hpp:20574
Represents an HTTP response to be sent to a client.
Definition HttpResponse.hpp:107
std::unordered_map< std::string, std::string, utils::CaseInsensitiveHash, utils::CaseInsensitiveEqual > headers
Definition HttpResponse.hpp:111
HttpResponse & status(HttpStatus code) &
Sets the HTTP status code of the response.
Definition HttpResponse.hpp:167
HttpResponse & send(const std::string &b) &
Sets the response body as plain text.
Definition HttpResponse.hpp:174
Definition legacy_namespaces.hpp:24
auto wrap_handler(Handler &&h) -> std::function< void(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)>
Definition HandlerWrapper.hpp:45
Represents an incoming HTTP request.
Definition HttpRequest.hpp:54
std::tuple< Args... > args_tuple
Definition HandlerWrapper.hpp:23
std::tuple< Args... > args_tuple
Definition HandlerWrapper.hpp:31
ReturnType result_type
Definition HandlerWrapper.hpp:30
ReturnType result_type
Definition HandlerWrapper.hpp:38
std::tuple< Args... > args_tuple
Definition HandlerWrapper.hpp:39
Definition HandlerWrapper.hpp:17