webcxx/src/Response.cpp
2022-10-07 16:24:12 +02:00

52 lines
1.3 KiB
C++

#include "Response.h"
#include "HTTPStatus.h"
#include <sstream>
#include <sys/socket.h>
static int socket_send(int fd, const char *str, size_t size, int flags) {
return send(fd, str, size, flags);
};
void webcxx::Response::set_status(int status_code)
{
status = status_code;
}
webcxx::Response::Response(int status_code, std::string content,
std::string content_type,
std::map<std::string, std::string> extra_headers)
: status(status_code), headers(extra_headers), content(content) {
headers["Content-Type"] = content_type;
if (content != "") {
std::ostringstream ss;
ss << content.size();
headers["Content-Length"] = ss.str();
}
headers["Server"] = "webcxx/0.1";
headers["Connection"] = "close";
}
std::string webcxx::Response::to_string() {
std::ostringstream result;
result << "HTTP/1.1 ";
result << status;
result << " ";
result << _webcxx_internal::http_status_codes[status];
result << "\r\n";
for (auto &header : headers) {
result << header.first;
result << ": ";
result << header.second;
result << "\r\n";
}
result << "\r\n";
if (content != "") {
result << content;
}
return result.str();
}
int webcxx::Response::send(int fd) {
std::string as_string = to_string();
return socket_send(fd, as_string.c_str(), as_string.size(), 0);
}