Skip to content

Commit

Permalink
fix simple_buf (#397)
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos authored Aug 26, 2023
1 parent 5fa6acb commit 3f44725
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
14 changes: 10 additions & 4 deletions include/cinatra/coro_http_client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ struct multipart_t {
size_t size = 0;
};

inline void free_simple_buffer(char *ptr) { ::free(ptr); }

class simple_buffer {
public:
inline static constexpr size_t sbuf_init_size = 4096;
Expand Down Expand Up @@ -150,6 +152,8 @@ class simple_buffer {

size_t size() const { return m_size; }

void increase_size(size_t size) { m_size += size; }

char *release() {
char *tmp = m_data;
m_size = 0;
Expand Down Expand Up @@ -329,11 +333,13 @@ class coro_http_client {
#endif

// return body_, the user will own body's lifetime.
std::unique_ptr<char[]> release_buf() {
auto release_buf() {
if (body_.empty()) {
return std::unique_ptr<char[]>(resp_chunk_str_.release());
return std::unique_ptr<char[], decltype(&free_simple_buffer)>(
resp_chunk_str_.release(), &free_simple_buffer);
}
return std::unique_ptr<char[]>(body_.release());
return std::unique_ptr<char[], decltype(&free_simple_buffer)>(
body_.release(), &free_simple_buffer);
}

// only make socket connet(or handshake) to the host
Expand Down Expand Up @@ -1309,7 +1315,7 @@ class coro_http_client {
ec) {
break;
}

body_.increase_size(size_to_read);
// Now get entire content, additional data will discard.
co_await handle_entire_content(data, content_len, is_ranges, ctx);
} while (0);
Expand Down
7 changes: 7 additions & 0 deletions tests/test_cinatra.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ TEST_CASE("test pass path not entire uri") {
coro_http_client client{};
auto r =
async_simple::coro::syncAwait(client.async_get("http://www.baidu.com"));
std::cout << r.resp_body.size() << "\n";
auto buf = client.release_buf();
std::cout << strlen(buf.get()) << "\n";
std::cout << buf << "\n";
CHECK(r.status >= 200);

r = async_simple::coro::syncAwait(client.async_get("http://www.baidu.com"));
Expand Down Expand Up @@ -565,6 +569,9 @@ TEST_CASE("test basic http request") {
coro_http_client client{};
std::string uri = "http://127.0.0.1:8090";
resp_data result = async_simple::coro::syncAwait(client.async_get(uri));
size_t size = result.resp_body.size();
auto buf = client.release_buf();
CHECK(size == strlen(buf.get()));
CHECK(result.resp_body == "hello world");

result = async_simple::coro::syncAwait(client.async_post(
Expand Down

0 comments on commit 3f44725

Please sign in to comment.