danicoin/src/HTTP/HttpResponse.cpp

85 lines
2 KiB
C++
Raw Normal View History

// Copyright (c) 2011-2016 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
2014-09-15 12:46:31 +00:00
#include "HttpResponse.h"
#include <stdexcept>
namespace {
2015-05-27 12:08:46 +00:00
const char* getStatusString(CryptoNote::HttpResponse::HTTP_STATUS status) {
2014-09-15 12:46:31 +00:00
switch (status) {
2015-05-27 12:08:46 +00:00
case CryptoNote::HttpResponse::STATUS_200:
2014-09-15 12:46:31 +00:00
return "200 OK";
2015-05-27 12:08:46 +00:00
case CryptoNote::HttpResponse::STATUS_404:
2014-09-15 12:46:31 +00:00
return "404 Not Found";
2015-05-27 12:08:46 +00:00
case CryptoNote::HttpResponse::STATUS_500:
2014-09-15 12:46:31 +00:00
return "500 Internal Server Error";
default:
throw std::runtime_error("Unknown HTTP status code is given");
}
return ""; //unaccessible
}
2015-05-27 12:08:46 +00:00
const char* getErrorBody(CryptoNote::HttpResponse::HTTP_STATUS status) {
switch (status) {
case CryptoNote::HttpResponse::STATUS_404:
return "Requested url is not found\n";
case CryptoNote::HttpResponse::STATUS_500:
2015-10-01 15:27:18 +00:00
return "Internal server error is occurred\n";
2015-05-27 12:08:46 +00:00
default:
throw std::runtime_error("Error body for given status is not available");
}
return ""; //unaccessible
}
2014-09-15 12:46:31 +00:00
} //namespace
2015-05-27 12:08:46 +00:00
namespace CryptoNote {
2014-09-15 12:46:31 +00:00
HttpResponse::HttpResponse() {
status = STATUS_200;
2015-07-30 15:22:07 +00:00
headers["Server"] = "CryptoNote-based HTTP server";
2014-09-15 12:46:31 +00:00
}
void HttpResponse::setStatus(HTTP_STATUS s) {
status = s;
2015-05-27 12:08:46 +00:00
if (status != HttpResponse::STATUS_200) {
setBody(getErrorBody(status));
}
2014-09-15 12:46:31 +00:00
}
void HttpResponse::addHeader(const std::string& name, const std::string& value) {
headers[name] = value;
}
void HttpResponse::setBody(const std::string& b) {
body = b;
if (!body.empty()) {
headers["Content-Length"] = std::to_string(body.size());
} else {
headers.erase("Content-Length");
}
}
std::ostream& HttpResponse::printHttpResponse(std::ostream& os) const {
os << "HTTP/1.1 " << getStatusString(status) << "\r\n";
for (auto pair: headers) {
os << pair.first << ": " << pair.second << "\r\n";
}
os << "\r\n";
if (!body.empty()) {
os << body;
}
return os;
}
2015-05-27 12:08:46 +00:00
} //namespace CryptoNote