pica/response/response.cpp

54 lines
1.3 KiB
C++
Raw Normal View History

// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
2023-11-21 22:19:08 +00:00
#include "response.h"
constexpr std::array<std::string_view, static_cast<uint8_t>(Response::Status::__size)> statusCodes = {
"Status: 200 OK",
"Status: 404 Not Found",
"Status: 405 Method Not Allowed",
"Status: 500 Internal Error"
};
constexpr std::array<std::string_view, static_cast<uint8_t>(Response::ContentType::__size)> contentTypes = {
2023-11-23 19:57:32 +00:00
"Content-type: text/plain",
"Content-type: application/json"
2023-11-21 22:19:08 +00:00
};
Response::Response():
status(Status::ok),
type(ContentType::text),
body()
{}
Response::Response(Status status):
status(status),
type(ContentType::text),
body()
{}
void Response::replyTo(Request& request) const {
// OStream out = status == Status::ok ?
// request.getOutputStream() :
// request.getErrorStream();
OStream out = request.getOutputStream();
out << statusCodes[static_cast<uint8_t>(status)];
if (!body.empty())
out << '\n'
<< contentTypes[static_cast<uint8_t>(type)]
2023-12-07 20:32:43 +00:00
<< '\n'
<< '\n'
2023-11-21 22:19:08 +00:00
<< body;
}
void Response::setBody(const std::string& body) {
2023-11-23 19:57:32 +00:00
type = ContentType::text;
2023-11-21 22:19:08 +00:00
Response::body = body;
}
2023-11-23 19:57:32 +00:00
void Response::setBody(const nlohmann::json& body) {
type = ContentType::json;
Response::body = body.dump();
}