From 595a530c6ac08f558f6dcd0a832eb18500a32106 Mon Sep 17 00:00:00 2001 From: qicosmos Date: Mon, 15 Jan 2024 15:27:42 +0800 Subject: [PATCH] add some methods (#489) --- include/cinatra/coro_http_connection.hpp | 30 ++++++++++++++++++++++++ include/cinatra/coro_http_request.hpp | 4 ++++ tests/test_coro_http_server.cpp | 5 ++++ 3 files changed, 39 insertions(+) diff --git a/include/cinatra/coro_http_connection.hpp b/include/cinatra/coro_http_connection.hpp index c4d2dd16..1ba03480 100644 --- a/include/cinatra/coro_http_connection.hpp +++ b/include/cinatra/coro_http_connection.hpp @@ -300,6 +300,36 @@ class coro_http_connection co_return true; } + std::string local_address() { + if (has_closed_) { + return ""; + } + + std::stringstream ss; + std::error_code ec; + ss << socket_.local_endpoint(ec); + if (ec) { + return ""; + } + return ss.str(); + } + + std::string remote_address() { + static std::string remote_addr; + if (has_closed_) { + return remote_addr; + } + + std::stringstream ss; + std::error_code ec; + ss << socket_.remote_endpoint(ec); + if (ec) { + return remote_addr; + } + remote_addr = ss.str(); + return ss.str(); + } + async_simple::coro::Lazy write_data(std::string_view message) { std::vector buffers; buffers.push_back(asio::buffer(message)); diff --git a/include/cinatra/coro_http_request.hpp b/include/cinatra/coro_http_request.hpp index cedf44a8..85383b24 100644 --- a/include/cinatra/coro_http_request.hpp +++ b/include/cinatra/coro_http_request.hpp @@ -169,6 +169,10 @@ class coro_http_request { return content_type::unknown; } + std::string_view get_url() { return parser_.url(); } + + std::string_view get_method() { return parser_.method(); } + std::string_view get_boundary() { auto content_type = get_header_value("content-type"); if (content_type.empty()) { diff --git a/tests/test_coro_http_server.cpp b/tests/test_coro_http_server.cpp index 726c56ce..0a5647e9 100644 --- a/tests/test_coro_http_server.cpp +++ b/tests/test_coro_http_server.cpp @@ -389,6 +389,11 @@ TEST_CASE("get post") { server.set_http_handler( "/test1", [](coro_http_request &req, coro_http_response &resp) { + CHECK(req.get_method() == "POST"); + CHECK(req.get_url() == "/test1"); + CHECK(req.get_conn()->local_address() == "127.0.0.1:9001"); + CHECK(req.get_conn()->remote_address().find("127.0.0.1:") != + std::string::npos); resp.add_header("Host", "Cinatra"); resp.set_status_and_content(cinatra::status_type::ok, "hello world"); });