From 689bb50234c42b912a57a679d3645d722b3b28c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Jaramago=20Fern=C3=A1ndez?= Date: Mon, 30 Mar 2020 10:10:41 +0200 Subject: [PATCH] Modified 'ProxySQL_RESTAPI_Server' constructor for being able to define generic extra GET endpoints --- include/ProxySQL_RESTAPI_Server.hpp | 16 ++++++++++++- lib/ProxySQL_RESTAPI_Server.cpp | 37 ++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/include/ProxySQL_RESTAPI_Server.hpp b/include/ProxySQL_RESTAPI_Server.hpp index fc0847e89d..a45d7907b0 100644 --- a/include/ProxySQL_RESTAPI_Server.hpp +++ b/include/ProxySQL_RESTAPI_Server.hpp @@ -3,6 +3,8 @@ #include "proxysql.h" #include "cpp.h" #include +#include +#include #include "httpserver.hpp" @@ -12,8 +14,20 @@ class ProxySQL_RESTAPI_Server { int port; pthread_t thread_id; std::unique_ptr endpoint; + std::vector>> _endpoints {}; public: - ProxySQL_RESTAPI_Server(int p); + ProxySQL_RESTAPI_Server( + int p, + std::vector< + std::pair< + std::string, + std::function(const httpserver::http_request&)>> + > endpoints = + std::vector< + std::pair< + std::string, + std::function(const httpserver::http_request&)>>> {} + ); ~ProxySQL_RESTAPI_Server(); void init(); void print_version(); diff --git a/lib/ProxySQL_RESTAPI_Server.cpp b/lib/ProxySQL_RESTAPI_Server.cpp index c61bf6bb17..fc101b416d 100644 --- a/lib/ProxySQL_RESTAPI_Server.cpp +++ b/lib/ProxySQL_RESTAPI_Server.cpp @@ -2,6 +2,7 @@ #include "cpp.h" #include "httpserver.hpp" +#include #include @@ -231,13 +232,34 @@ class sync_resource : public http_resource { }; +class gen_get_endpoint : public http_resource { +private: + std::function(const http_request&)> _get_fn {}; +public: + gen_get_endpoint(std::function(const http_request&)> get_fn) : + _get_fn(get_fn) + {} + + const std::shared_ptr render_GET(const http_request& req) override { + return this->_get_fn(req); + } +}; + void * restapi_server_thread(void *arg) { httpserver::webserver * ws = (httpserver::webserver *)arg; ws->start(true); return NULL; } -ProxySQL_RESTAPI_Server::ProxySQL_RESTAPI_Server(int p) { +using std::vector; +using std::pair; +using std::function; +using std::shared_ptr; + +ProxySQL_RESTAPI_Server::ProxySQL_RESTAPI_Server( + int p, + vector(const http_request&)>>> endpoints +) { ws = std::unique_ptr(new webserver(create_webserver(p))); auto sr = new sync_resource(); @@ -248,6 +270,19 @@ ProxySQL_RESTAPI_Server::ProxySQL_RESTAPI_Server(int p) { perror("Thread creation"); exit(EXIT_FAILURE); } + + for (const auto& id_endpoint : endpoints) { + const auto& endpoint_route { id_endpoint.first }; + auto endpoint_fn { id_endpoint.second }; + auto endpoint_res { + std::unique_ptr( + new gen_get_endpoint(endpoint_fn) + ) + }; + + ws->register_resource(endpoint_route, endpoint_res.get(), true); + _endpoints.push_back({endpoint_route, std::move(endpoint_res)}); + } } ProxySQL_RESTAPI_Server::~ProxySQL_RESTAPI_Server() {