58 lines
1.8 KiB
C++
58 lines
1.8 KiB
C++
#pragma once
|
|
|
|
#include <string>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <cstdlib>
|
|
|
|
#include "common.hpp"
|
|
|
|
struct ServerConfig {
|
|
std::string address;
|
|
int port;
|
|
int threads;
|
|
};
|
|
|
|
struct DatabaseConfig {
|
|
std::string host;
|
|
int port;
|
|
std::string dbname;
|
|
std::string user;
|
|
std::string password;
|
|
};
|
|
|
|
struct AppConfig {
|
|
ServerConfig server;
|
|
DatabaseConfig database;
|
|
|
|
static AppConfig loadFromFile(const std::string& filename) {
|
|
std::ifstream file(filename);
|
|
if (!file.is_open()) {
|
|
throw std::runtime_error("Cannot open config file: " + filename);
|
|
}
|
|
|
|
json j;
|
|
file >> j;
|
|
|
|
AppConfig config;
|
|
config.server.address = j.at("server").at("address");
|
|
config.server.port = j.at("server").at("port");
|
|
config.server.threads = j.at("server").at("threads");
|
|
config.database.host = j.at("database").value("host", "localhost");
|
|
config.database.port = j.at("database").value("port", 5432);
|
|
config.database.dbname = j.at("database").value("dbname", "");
|
|
config.database.user = j.at("database").value("user", "");
|
|
config.database.password = j.at("database").value("password", "");
|
|
|
|
// Environment variables override config file
|
|
if (const char* val = std::getenv("DB_HOST")) config.database.host = val;
|
|
if (const char* val = std::getenv("DB_PORT")) config.database.port = std::stoi(val);
|
|
if (const char* val = std::getenv("DB_NAME")) config.database.dbname = val;
|
|
if (const char* val = std::getenv("DB_USER")) config.database.user = val;
|
|
if (const char* val = std::getenv("DB_PASSWORD")) config.database.password = val;
|
|
|
|
return config;
|
|
}
|
|
};
|
|
|