Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve the duplicate registration key issue #142

Merged
merged 2 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions include/rest_rpc/router.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,24 @@ class router : asio::noncopyable {
template <bool is_pub = false, typename Function>
void register_handler(std::string const &name, Function f, bool pub = false) {
uint32_t key = MD5::MD5Hash32(name.data());
key2func_name_.emplace(key, name);
return register_nonmember_func<is_pub>(key, std::move(f));
if (key2func_name_.find(key) != key2func_name_.end()) {
throw std::invalid_argument("duplicate registration key !");
} else {
key2func_name_.emplace(key, name);
return register_nonmember_func<is_pub>(key, std::move(f));
}
}

template <bool is_pub = false, typename Function, typename Self>
void register_handler(std::string const &name, const Function &f,
Self *self) {
uint32_t key = MD5::MD5Hash32(name.data());
key2func_name_.emplace(key, name);
return register_member_func<is_pub>(key, f, self);
if (key2func_name_.find(key) != key2func_name_.end()) {
throw std::invalid_argument("duplicate registration key !");
} else {
key2func_name_.emplace(key, name);
return register_member_func<is_pub>(key, f, self);
}
}

void remove_handler(std::string const &name) {
Expand Down
20 changes: 20 additions & 0 deletions tests/test_rest_rpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,26 @@ TEST_CASE("test_server_delay_response") {
server.async_run();
std::this_thread::sleep_for(std::chrono::milliseconds(200));

rpc_client client("127.0.0.1", 9000);
bool r = client.connect();
CHECK(r);
auto result = client.call<std::string>("delay_echo", "test_delay_echo");
CHECK_EQ(result, "test_delay_echo");
}
TEST_CASE("test_server_duplicate_registration_key") {
rpc_server server(9000, std::thread::hardware_concurrency());
server.register_handler("delay_echo", delay_echo);
try {
server.register_handler("delay_echo", delay_echo);
} catch (const std::exception &e) {
string_view ew{e.what()};
std::cerr << ew << '\n';
CHECK_EQ(ew, "duplicate registration key !");
}

server.async_run();
std::this_thread::sleep_for(std::chrono::milliseconds(200));

rpc_client client("127.0.0.1", 9000);
bool r = client.connect();
CHECK(r);
Expand Down
Loading