From 5313e640554675def014d1e46f36004d75acc3d4 Mon Sep 17 00:00:00 2001 From: Shantanav Date: Tue, 11 Aug 2026 16:49:28 +0530 Subject: [PATCH] feat: add HttpRequest hasBody helper --- src/HttpParser.h | 5 +++++ tests/HttpParser.cpp | 22 +++++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/HttpParser.h b/src/HttpParser.h index f5958986d..4239b1774 100644 --- a/src/HttpParser.h +++ b/src/HttpParser.h @@ -145,6 +145,11 @@ struct HttpRequest { return std::string_view(headers->key.data(), headers->key.length()); } + /* Returns whether the request declares a body that can be delivered through onData. */ + bool hasBody() { + return getHeader("content-length").length() || getHeader("transfer-encoding").length(); + } + /* Returns the raw querystring as a whole, still encoded */ std::string_view getQuery() { if (querySeparator < headers->value.length()) { diff --git a/tests/HttpParser.cpp b/tests/HttpParser.cpp index a1b75317a..e245ec19d 100644 --- a/tests/HttpParser.cpp +++ b/tests/HttpParser.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "../src/HttpParser.h" @@ -16,6 +17,8 @@ int main() { std::cout << httpRequest->getMethod() << std::endl; + assert(!httpRequest->hasBody()); + for (auto [key, value] : *httpRequest) { std::cout << key << ": " << value << std::endl; } @@ -35,4 +38,21 @@ int main() { std::cout << "HTTP DONE" << std::endl; -} \ No newline at end of file + std::string bodyRequest = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 4\r\n\r\ntest"; + bodyRequest.append(8, '\0'); + uWS::HttpParser bodyParser; + auto [bodyErr, bodyUser] = bodyParser.consumePostPadded( + bodyRequest.data(), (unsigned int) bodyRequest.length() - 8, user, reserved, + [](void *user, uWS::HttpRequest *httpRequest) -> void * { + assert(httpRequest->hasBody()); + return user; + }, + [](void *user, std::string_view data, bool) -> void * { + assert(data == "test"); + return user; + } + ); + assert(bodyErr == 0); + assert(bodyUser == user); + +}