Update GetJson

This commit is contained in:
Paulius Gerve 2025-02-28 10:02:15 +02:00
parent 17b528489b
commit f377a4e66d

View file

@ -44,10 +44,14 @@ inline std::optional<std::string> get_env_utf8(const std::string& name) {
} }
inline const nlohmann::json& GetJson() { inline const nlohmann::json& GetJson() {
static const nlohmann::json jsonConfig = []() { static std::once_flag initFlag;
std::string jsonString; static nlohmann::json jsonConfig;
int index = 1;
std::call_once(initFlag, []() {
std::string jsonString;
// First try the chunked environment variables
int index = 1;
while (true) { while (true) {
std::string envName = "CAMOU_CONFIG_" + std::to_string(index); std::string envName = "CAMOU_CONFIG_" + std::to_string(index);
auto partialConfig = get_env_utf8(envName); auto partialConfig = get_env_utf8(envName);
@ -57,23 +61,36 @@ inline const nlohmann::json& GetJson() {
index++; index++;
} }
// If no chunked variables found, try the original CAMOU_CONFIG
if (jsonString.empty()) { if (jsonString.empty()) {
// Check for the original CAMOU_CONFIG as fallback
auto originalConfig = get_env_utf8("CAMOU_CONFIG"); auto originalConfig = get_env_utf8("CAMOU_CONFIG");
if (originalConfig) jsonString = *originalConfig; if (originalConfig) {
jsonString = *originalConfig;
}
} }
if (jsonString.empty()) return nlohmann::json{}; // If still empty, return an empty JSON object
if (jsonString.empty()) {
// Validate jsonConfig = nlohmann::json{};
if (!nlohmann::json::accept(jsonString)) { return;
printf_stderr("ERROR: Invalid JSON passed to CAMOU_CONFIG!\n");
return nlohmann::json{};
} }
nlohmann::json result = nlohmann::json::parse(jsonString); // Validate and parse the JSON
return result; try {
}(); if (!nlohmann::json::accept(jsonString)) {
printf_stderr("ERROR: Invalid JSON passed to CAMOU_CONFIG!\n");
jsonConfig = nlohmann::json{};
return;
}
jsonConfig = nlohmann::json::parse(jsonString);
} catch (const nlohmann::json::exception& e) {
printf_stderr("ERROR: JSON parsing failed: %s\n", e.what());
jsonConfig = nlohmann::json{};
}
});
// Return the cached JSON object
return jsonConfig; return jsonConfig;
} }