#include "dnsdist-lua.hh"
#include "dnsdist-web.hh"
-void registerWebHandler(const std::string& endpoint, std::function<void(const YaHTTP::Request&, YaHTTP::Response&)> handler);
+void registerWebHandler(const std::string& endpoint, std::function<void(const YaHTTP::Request&, YaHTTP::Response&)> handler, bool isLua);
void setupLuaWeb(LuaContext& luaCtx)
{
#ifndef DISABLE_LUA_WEB_HANDLERS
luaCtx.writeFunction("registerWebHandler", [](const std::string& path, std::function<void(const YaHTTP::Request*, YaHTTP::Response*)> handler) {
/* LuaWrapper does a copy for objects passed by reference, so we pass a pointer */
- registerWebHandler(path, [handler](const YaHTTP::Request& req, YaHTTP::Response& resp) { handler(&req, &resp); });
+ registerWebHandler(path, [handler](const YaHTTP::Request& req, YaHTTP::Response& resp) { handler(&req, &resp); }, true);
});
luaCtx.registerMember<std::string(YaHTTP::Request::*)>("path", [](const YaHTTP::Request& req) -> std::string { return req.url.path; }, [](YaHTTP::Request& req, const std::string& path) { (void) path; });
});
#endif /* DISABLE_LUA_WEB_HANDLERS */
}
-
}
using WebHandler = std::function<void(const YaHTTP::Request&, YaHTTP::Response&)>;
-static SharedLockGuarded<std::unordered_map<std::string, WebHandler>> s_webHandlers;
+struct WebHandlerContext
+{
+ WebHandler d_handler;
+ bool d_isLua;
+};
+
+static SharedLockGuarded<std::unordered_map<std::string, WebHandlerContext>> s_webHandlers;
-void registerWebHandler(const std::string& endpoint, WebHandler handler);
+void registerWebHandler(const std::string& endpoint, WebHandler handler, bool isLua = false);
-void registerWebHandler(const std::string& endpoint, WebHandler handler)
+void registerWebHandler(const std::string& endpoint, WebHandler handler, bool isLua)
{
auto handlers = s_webHandlers.write_lock();
- (*handlers)[endpoint] = std::move(handler);
+ (*handlers).emplace(std::make_pair(endpoint, WebHandlerContext{std::move(handler), isLua}));
}
void clearWebHandlers()
resp.status = 405;
}
else {
- WebHandler handler;
+ std::optional<WebHandlerContext> handlerCtx{std::nullopt};
{
auto handlers = s_webHandlers.read_lock();
const auto webHandlersIt = handlers->find(req.url.path);
if (webHandlersIt != handlers->end()) {
- handler = webHandlersIt->second;
+ handlerCtx = webHandlersIt->second;
}
}
- if (handler) {
- handler(req, resp);
+ if (handlerCtx) {
+ if (handlerCtx->d_isLua) {
+ auto lua = g_lua.lock();
+ handlerCtx->d_handler(req, resp);
+ }
+ else {
+ handlerCtx->d_handler(req, resp);
+ }
}
else {
resp.status = 404;