|
|
|
|
#ifndef _TR_UTIL_HPP_
|
|
|
|
|
#define _TR_UTIL_HPP_
|
|
|
|
|
|
|
|
|
|
#include <boost/regex.hpp>
|
|
|
|
|
#include <json.hpp>
|
|
|
|
|
#include <unordered_map>
|
|
|
|
|
|
|
|
|
|
namespace util {
|
|
|
|
|
class uri {
|
|
|
|
|
public:
|
|
|
|
|
auto static parse(const std::string &request_path) {
|
|
|
|
|
std::unordered_map<std::string, std::string> options;
|
|
|
|
|
std::string option, value;
|
|
|
|
|
bool collect = false;
|
|
|
|
|
for (auto &c : request_path) {
|
|
|
|
|
switch (c) {
|
|
|
|
|
case '&':
|
|
|
|
|
options.insert(std::make_pair(option, value));
|
|
|
|
|
option = "";
|
|
|
|
|
collect = true;
|
|
|
|
|
break;
|
|
|
|
|
case '?':
|
|
|
|
|
collect = true;
|
|
|
|
|
break;
|
|
|
|
|
case '=':
|
|
|
|
|
collect = false;
|
|
|
|
|
value = "";
|
|
|
|
|
break;
|
|
|
|
|
default:
|
|
|
|
|
if (collect)
|
|
|
|
|
option += c;
|
|
|
|
|
else
|
|
|
|
|
value += c;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (!option.empty() || !value.empty())
|
|
|
|
|
options.insert(std::make_pair(option, value));
|
|
|
|
|
return options;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
const boost::regex regex("@(https?|ftp)://(-\\.)?([^\\s/?\\.#-]+\\.?)+(/[^\\s]*)?$@", boost::regex_constants::perl | boost::regex_constants::icase);
|
|
|
|
|
|
|
|
|
|
class json {
|
|
|
|
|
public:
|
|
|
|
|
/*! @brief Wrapper for nlohmann::json::parse. If the parse fails, result.is_null() will be */
|
|
|
|
|
static nlohmann::json parse(std::istream &istream) {
|
|
|
|
|
try {
|
|
|
|
|
return nlohmann::json::parse(istream);
|
|
|
|
|
} catch (const std::invalid_argument &exp) {
|
|
|
|
|
}
|
|
|
|
|
return nlohmann::json(nullptr);
|
|
|
|
|
}
|
|
|
|
|
/*! @brief wrapper around nlohmann::json::parse, but object returns null on throw */
|
|
|
|
|
static nlohmann::json parse(const std::string &string) {
|
|
|
|
|
try {
|
|
|
|
|
return nlohmann::json::parse(string);
|
|
|
|
|
} catch (const std::invalid_argument &exp) {
|
|
|
|
|
}
|
|
|
|
|
return nlohmann::json(nullptr);
|
|
|
|
|
}
|
|
|
|
|
static bool has_property(const std::string &key, const nlohmann::json &object) {
|
|
|
|
|
auto it = object.find(key);
|
|
|
|
|
return it != object.end();
|
|
|
|
|
}
|
|
|
|
|
template <class T>
|
|
|
|
|
static auto get(const std::string &key, const nlohmann::json &object, const T &default_value) {
|
|
|
|
|
if (has_property(key, object)) {
|
|
|
|
|
T r;
|
|
|
|
|
try {
|
|
|
|
|
r = object[key]; //TODO fix use json parser where a non-throwable exist
|
|
|
|
|
} catch (const std::exception &) {
|
|
|
|
|
return default_value;
|
|
|
|
|
}
|
|
|
|
|
return r;
|
|
|
|
|
}
|
|
|
|
|
return default_value;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#endif
|