From 2ce61402bb4a300f6b79a21efb924d1a0306bb0e Mon Sep 17 00:00:00 2001 From: hagen Date: Tue, 24 May 2016 00:00:00 +0000 Subject: [PATCH] * HTTP.{cpp,h} * add 'body' member ot HTTPRes * change HTTPRes::to_string() to add 'Date', 'Content-Length' headers and body --- HTTP.cpp | 12 ++++++++++++ HTTP.h | 14 +++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/HTTP.cpp b/HTTP.cpp index 6747c35b..254cab95 100644 --- a/HTTP.cpp +++ b/HTTP.cpp @@ -334,12 +334,24 @@ namespace http { } std::string HTTPRes::to_string() { + if (version == "HTTP/1.1" && headers.count("Date") == 0) { + std::string date; + gen_rfc1123_date(date); + add_header("Date", date.c_str()); + } + if (status == "OK" && code != 200) + status = HTTPCodeToStatus(code); // update + if (body.length() > 0 && headers.count("Content-Length") == 0) + add_header("Content-Length", std::to_string(body.length()).c_str()); + /* build response */ std::stringstream ss; ss << version << " " << code << " " << status << CRLF; for (auto & h : headers) { ss << h.first << ": " << h.second << CRLF; } ss << CRLF; + if (body.length() > 0) + ss << body; return ss.str(); } diff --git a/HTTP.h b/HTTP.h index e13fe547..7f73285f 100644 --- a/HTTP.h +++ b/HTTP.h @@ -85,6 +85,12 @@ namespace http { std::string version; std::string status; unsigned short int code; + /** simplifies response generation + * If this variable is set: + * a) Content-Length header will be added if missing + * b) contents of body will be included in response + */ + std::string body; HTTPRes (): version("HTTP/1.1"), status("OK"), code(200) {} @@ -96,7 +102,13 @@ namespace http { int parse(const char *buf, size_t len); int parse(const std::string& buf); - /** @brief Serialize HTTP response to string */ + /** + * @brief Serialize HTTP response to string + * @note If version is set to HTTP/1.1, and Date header is missing, + * it will be generated based on current time and added to headers + * @note If body member is set and Content-Length header is missing, + * this header will be added, based on body's length + */ std::string to_string(); /** @brief Checks that response declared as chunked data */