Skip to content

Commit 07de8a5

Browse files
committed
Config.hpp
1 parent f03b9ee commit 07de8a5

4 files changed

Lines changed: 33 additions & 5 deletions

File tree

section5/Config.hpp

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@ class Config final
2121
using vm_type = std::shared_ptr<lua_State>;
2222
using value_type = luabridge::LuaRef;
2323

24-
//using string_type = std::string;
24+
using string_type = std::string;
2525
using string_view_type = const std::string&;
26+
using regex_type = std::regex;
27+
using match_type = std::smatch;
2628
public:
2729
Config() noexcept
2830
{
@@ -37,17 +39,28 @@ class Config final
3739
{
3840
auto status = luaL_dofile(m_vm.get(), filename.c_str());
3941

40-
if (!status) {
42+
if (status != 0) {
4143
throw std::runtime_error("failed to parse config");
4244
}
4345
}
4446

45-
value_type get(string_view_type key) const
47+
value_type get(string_view_type key)
4648
{
47-
return luabridge::getGlobal(m_vm.get(), key.c_str());
49+
if (!std::regex_match(key, m_what, m_conf_reg)) {
50+
throw std::runtime_error("config key error");
51+
}
52+
53+
auto w1 = m_what[1].str();
54+
auto w2 = m_what[2].str();
55+
56+
return luabridge::getGlobal(
57+
m_vm.get(), w1.c_str())[w2];
4858
}
4959
private:
5060
vm_type m_vm {luaL_newstate(), lua_close};
61+
62+
regex_type m_conf_reg {R"(^(\w+)\.(\w+)$)"};
63+
match_type m_what;
5164
};
5265

5366
END_NAMESPACE(cpp_study)

section5/conf.lua

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,7 @@ config = {
2121
time_interval = 1,
2222

2323
}
24+
25+
-- debug: luajit conf.lua
26+
27+
--print(config.http_addr)

section5/cpplang.hpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <unordered_set>
1515
#include <unordered_map>
1616
#include <algorithm>
17+
#include <regex>
1718

1819
#include <atomic>
1920
#include <future>

section5/srv.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ auto debug_print = [](auto& b)
3333
};
3434

3535
int main()
36+
try
3637
{
3738
cout << "hello cpp_study server" << endl;
3839

@@ -85,7 +86,16 @@ int main()
8586
}
8687
};
8788

88-
auto fu = std::async(cycle, "tcp://127.0.0.1:5555");
89+
Config conf;
90+
conf.load("./conf.lua");
91+
92+
string listen_addr = conf.get("config.zmq_ipc_addr");
93+
94+
auto fu = std::async(cycle, listen_addr);
8995

9096
fu.wait();
9197
}
98+
catch(std::exception& e)
99+
{
100+
std::cerr << e.what() << std::endl;
101+
}

0 commit comments

Comments
 (0)