Support LOCAL_ADDR and LOCAL_PORT header in client Request ()

Having the local address/port is useful if the server is bound to
all interfaces, e.g. to serve different content for developers
on localhost only.
This commit is contained in:
Ingo Bauersachs 2022-12-06 14:23:09 +01:00 committed by GitHub
parent c8c1c3d376
commit 8f32271e8c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 63 additions and 8 deletions

View file

@ -22,8 +22,6 @@ public:
ssize_t write(const std::string &s) { return write(s.data(), s.size()); }
std::string get_remote_addr() const { return ""; }
bool is_readable() const override { return true; }
bool is_writable() const override { return true; }
@ -33,6 +31,11 @@ public:
port = 8080;
}
void get_local_ip_and_port(std::string &ip, int &port) const override {
ip = "127.0.0.1";
port = 8080;
}
socket_t socket() const override { return 0; }
private:

View file

@ -1521,6 +1521,17 @@ protected:
std::stoi(req.get_header_value("REMOTE_PORT")));
res.set_content(remote_addr.c_str(), "text/plain");
})
.Get("/local_addr",
[&](const Request &req, Response &res) {
EXPECT_TRUE(req.has_header("LOCAL_PORT"));
EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
auto local_addr = req.get_header_value("LOCAL_ADDR");
auto local_port = req.get_header_value("LOCAL_PORT");
EXPECT_EQ(req.local_addr, local_addr);
EXPECT_EQ(req.local_port, std::stoi(local_port));
res.set_content(local_addr.append(":").append(local_port),
"text/plain");
})
.Get("/endwith%",
[&](const Request & /*req*/, Response &res) {
res.set_content("Hello World!", "text/plain");
@ -2810,6 +2821,15 @@ TEST_F(ServerTest, GetMethodRemoteAddr) {
EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
}
TEST_F(ServerTest, GetMethodLocalAddr) {
auto res = cli_.Get("/local_addr");
ASSERT_TRUE(res);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
res->body == std::string("127.0.0.1:").append(to_string(PORT)));
}
TEST_F(ServerTest, HTTPResponseSplitting) {
auto res = cli_.Get("/http_response_splitting");
ASSERT_TRUE(res);