coyote/config.cpp

57 lines
1.8 KiB
C++

#include <stdexcept>
#include <nlohmann/json.hpp>
#include "file.h"
#include "config.h"
Config config;
void load_config(const char* path) {
File config_file(path, "r");
config = nlohmann::json::parse(config_file.get());
}
RedisConfig get_redis_config(const nlohmann::json& j) {
using namespace std::string_literals;
RedisConfig redis_config;
const nlohmann::json& connection = j.at("connection");
const std::string& connection_type = connection.at("type").get_ref<const std::string&>();
if (connection_type == "ip") {
redis_config.connection_method = IPConnection{
connection.at("address").get<std::string>(),
connection.at("port").get<int>()
};
} else if (connection_type == "unix") {
redis_config.connection_method = UnixConnection{connection.at("unix").get<std::string>()};
} else {
throw std::invalid_argument("Unknown redis connection type: "s + connection_type);
}
if (j.at("username").is_string()) {
redis_config.username = j["username"].get<std::string>();
}
if (j.at("password").is_string()) {
redis_config.password = j["password"].get<std::string>();
}
return redis_config;
}
void from_json(const nlohmann::json& j, Config& conf) {
using namespace std::string_literals;
j.at("bind_host").get_to(conf.bind_host);
j.at("bind_port").get_to(conf.bind_port);
if (conf.bind_port < 0) {
throw std::invalid_argument("Invalid port to bind to: "s + std::to_string(conf.bind_port));
}
if (j.at("canonical_origin").is_string()) {
conf.canonical_origin = j["canonical_origin"].get<std::string>();
}
if (j.at("redis").at("enabled").get<bool>()) {
conf.redis_config = get_redis_config(j["redis"]);
}
}