Browse Source

* HTTP.{cpp,h} * add 'body' member ot HTTPRes * change HTTPRes::to_string() to add 'Date', 'Content-Length' headers and body

pull/503/head
hagen 9 years ago
parent
commit
2ce61402bb
  1. 12
      HTTP.cpp
  2. 14
      HTTP.h

12
HTTP.cpp

@ -334,12 +334,24 @@ namespace http {
} }
std::string HTTPRes::to_string() { 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; std::stringstream ss;
ss << version << " " << code << " " << status << CRLF; ss << version << " " << code << " " << status << CRLF;
for (auto & h : headers) { for (auto & h : headers) {
ss << h.first << ": " << h.second << CRLF; ss << h.first << ": " << h.second << CRLF;
} }
ss << CRLF; ss << CRLF;
if (body.length() > 0)
ss << body;
return ss.str(); return ss.str();
} }

14
HTTP.h

@ -85,6 +85,12 @@ namespace http {
std::string version; std::string version;
std::string status; std::string status;
unsigned short int code; 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) {} 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 char *buf, size_t len);
int parse(const std::string& buf); 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(); std::string to_string();
/** @brief Checks that response declared as chunked data */ /** @brief Checks that response declared as chunked data */

Loading…
Cancel
Save