diff options
author | stickies-v <stickies-v@protonmail.com> | 2022-01-05 14:28:12 +0000 |
---|---|---|
committer | stickies-v <stickies-v@protonmail.com> | 2022-03-10 12:01:54 +0100 |
commit | a09497614e9bb603fff36286d9611a25b23eeb02 (patch) | |
tree | a1c484e29c8f7c32555b580bfbf44661aad6426b /src/httpserver.cpp | |
parent | fff771ee864975cee8c831651239bac95503c37a (diff) |
Add GetQueryParameter helper function
Easily get the query parameter from the URI, with optional default value.
Diffstat (limited to 'src/httpserver.cpp')
-rw-r--r-- | src/httpserver.cpp | 37 |
1 files changed, 35 insertions, 2 deletions
diff --git a/src/httpserver.cpp b/src/httpserver.cpp index e00c68585e..2212097754 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -23,6 +23,7 @@ #include <deque> #include <memory> +#include <optional> #include <stdio.h> #include <stdlib.h> #include <string> @@ -30,11 +31,12 @@ #include <sys/types.h> #include <sys/stat.h> -#include <event2/thread.h> #include <event2/buffer.h> #include <event2/bufferevent.h> -#include <event2/util.h> +#include <event2/http.h> #include <event2/keyvalq_struct.h> +#include <event2/thread.h> +#include <event2/util.h> #include <support/events.h> @@ -639,6 +641,37 @@ HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() const } } +std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const +{ + const char* uri{evhttp_request_get_uri(req)}; + + return GetQueryParameterFromUri(uri, key); +} + +std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key) +{ + evhttp_uri* uri_parsed{evhttp_uri_parse(uri)}; + const char* query{evhttp_uri_get_query(uri_parsed)}; + std::optional<std::string> result; + + if (query) { + // Parse the query string into a key-value queue and iterate over it + struct evkeyvalq params_q; + evhttp_parse_query_str(query, ¶ms_q); + + for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) { + if (param->key == key) { + result = param->value; + break; + } + } + evhttp_clear_headers(¶ms_q); + } + evhttp_uri_free(uri_parsed); + + return result; +} + void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler) { LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch); |