config.cpp 785 B

1234567891011121314151617181920212223242526272829
  1. #include "config.hpp"
  2. #include <fstream>
  3. #include <stdexcept>
  4. namespace svapi {
  5. Config Config::fromJson(const nlohmann::json& j) {
  6. Config c;
  7. c.logLevel = j.value("log_level", c.logLevel);
  8. if (j.contains("http") && j["http"].is_object()) {
  9. const auto& h = j["http"];
  10. c.httpBind = h.value("bind_address", c.httpBind);
  11. c.httpPort = h.value("port", c.httpPort);
  12. }
  13. if (j.contains("database") && j["database"].is_object()) {
  14. c.dbAddress = j["database"].value("address", c.dbAddress);
  15. }
  16. return c;
  17. }
  18. Config Config::load(const std::string& path) {
  19. std::ifstream f(path);
  20. if (!f) throw std::runtime_error("cannot open config file: " + path);
  21. nlohmann::json j;
  22. f >> j;
  23. return fromJson(j);
  24. }
  25. } // namespace svapi