pica/response/response.cpp
2024-01-21 16:23:48 -03:00

79 lines
1.9 KiB
C++

//SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#include "response.h"
#include "request/request.h"
constexpr std::array<uint16_t, static_cast<uint8_t>(Response::Status::__size)> statusCodes = {
200,
400,
401,
403,
404,
405,
409,
500
};
constexpr std::array<std::string_view, static_cast<uint8_t>(Response::Status::__size)> statuses = {
"Status: 200 OK",
"Status: 400 Bad Request",
"Status: 401 Unauthorized",
"Status: 403 Forbidden",
"Status: 404 Not Found",
"Status: 405 Method Not Allowed",
"Status: 409 Conflict",
"Status: 500 Internal Error"
};
constexpr std::array<std::string_view, static_cast<uint8_t>(Response::ContentType::__size)> contentTypes = {
"Content-Type: text/plain",
"Content-Type: application/json"
};
Response::Response(Request& request):
request(request),
status(Status::ok),
type(ContentType::text),
body()
{}
Response::Response(Request& request, Status status):
request(request),
status(status),
type(ContentType::text),
body()
{}
void Response::send() const {
// OStream out = status == Status::ok ?
// request.getOutputStream() :
// request.getErrorStream();
OStream out = request.getOutputStream();
out << statuses[static_cast<uint8_t>(status)] << "\r\n";
if (!body.empty())
out << contentTypes[static_cast<uint8_t>(type)] << "\r\n"
<< "\r\n"
<< body;
else
out << "\r\n";
request.responseIsComplete();
}
uint16_t Response::statusCode() const {
return statusCodes[static_cast<uint8_t>(status)];
}
void Response::setBody(const std::string& body) {
type = ContentType::text;
Response::body = body;
}
void Response::setBody(const nlohmann::json& body) {
type = ContentType::json;
Response::body = body.dump();
}