Skip to content

Commit

Permalink
cache remote addres
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos committed Apr 24, 2024
1 parent 046ec0c commit 5292ee7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
28 changes: 19 additions & 9 deletions include/ylt/standalone/cinatra/coro_http_connection.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -392,9 +392,19 @@ class coro_http_connection
co_return true;
}

std::string local_address() { return get_address_impl(false); }
std::string local_address() {
std::string addr;
set_address_impl(addr, false);
return addr;
}

std::string remote_address() { return get_address_impl(); }
std::string remote_address() {
if (!remote_addr_.empty()) {
return remote_addr_;
}
set_address_impl(remote_addr_, false);
return remote_addr_;
}

void set_multi_buf(bool r) { multi_buf_ = r; }

Expand Down Expand Up @@ -843,22 +853,21 @@ class coro_http_connection
}
}

std::string get_address_impl(bool remote = true) {
void set_address_impl(std::string &address, bool remote = true) {
if (has_closed_) {
return "";
return;
}

std::error_code ec;
auto pt = remote ? socket_.remote_endpoint(ec) : socket_.local_endpoint(ec);
if (ec) {
return "";
return;
}
auto addr = pt.address().to_string(ec);
address = pt.address().to_string(ec);
if (ec) {
return "";
return;
}
addr.append(":").append(std::to_string(pt.port()));
return addr;
address.append(":").append(std::to_string(pt.port()));
}

private:
Expand Down Expand Up @@ -898,5 +907,6 @@ class coro_http_connection
std::function<void(coro_http_request &, coro_http_response &)>
default_handler_ = nullptr;
std::string chunk_size_str_;
std::string remote_addr_;
};
} // namespace cinatra
2 changes: 2 additions & 0 deletions src/coro_http/examples/example.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,8 @@ async_simple::coro::Lazy<void> basic_usage() {

server.set_http_handler<POST, PUT>(
"/post", [](coro_http_request &req, coro_http_response &resp) {
assert(resp.get_conn()->remote_address().find("127.0.0.1") !=
std::string::npos);
assert(resp.get_conn()->remote_address().find("127.0.0.1") !=
std::string::npos);
assert(resp.get_conn()->local_address() == "127.0.0.1:9001");
Expand Down

0 comments on commit 5292ee7

Please sign in to comment.