2023-12-10 23:23:15 +00:00
|
|
|
// 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"
|
|
|
|
|
2023-12-22 23:25:20 +00:00
|
|
|
#include "request/request.h"
|
|
|
|
|
|
|
|
constexpr std::array<uint16_t, static_cast<uint8_t>(Response::Status::__size)> statusCodes = {
|
|
|
|
200,
|
|
|
|
400,
|
|
|
|
401,
|
|
|
|
404,
|
|
|
|
405,
|
|
|
|
409,
|
|
|
|
500
|
|
|
|
};
|
|
|
|
|
|
|
|
constexpr std::array<std::string_view, static_cast<uint8_t>(Response::Status::__size)> statuses = {
|
2023-11-21 22:19:08 +00:00
|
|
|
"Status: 200 OK",
|
2023-12-22 23:25:20 +00:00
|
|
|
"Status: 400 Bad Request",
|
|
|
|
"Status: 401 Unauthorized",
|
2023-11-21 22:19:08 +00:00
|
|
|
"Status: 404 Not Found",
|
|
|
|
"Status: 405 Method Not Allowed",
|
2023-12-22 23:25:20 +00:00
|
|
|
"Status: 409 Conflict",
|
2023-11-21 22:19:08 +00:00
|
|
|
"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
|
|
|
};
|
|
|
|
|
2023-12-13 20:33:11 +00:00
|
|
|
Response::Response(Request& request):
|
|
|
|
request(request),
|
2023-11-21 22:19:08 +00:00
|
|
|
status(Status::ok),
|
|
|
|
type(ContentType::text),
|
|
|
|
body()
|
|
|
|
{}
|
|
|
|
|
2023-12-13 20:33:11 +00:00
|
|
|
Response::Response(Request& request, Status status):
|
|
|
|
request(request),
|
2023-11-21 22:19:08 +00:00
|
|
|
status(status),
|
|
|
|
type(ContentType::text),
|
|
|
|
body()
|
|
|
|
{}
|
|
|
|
|
2023-12-13 20:33:11 +00:00
|
|
|
void Response::send() const {
|
2023-11-21 22:19:08 +00:00
|
|
|
// OStream out = status == Status::ok ?
|
|
|
|
// request.getOutputStream() :
|
|
|
|
// request.getErrorStream();
|
2023-12-22 23:25:20 +00:00
|
|
|
OStream out = request.getOutputStream();
|
2023-11-21 22:19:08 +00:00
|
|
|
|
2023-12-22 23:25:20 +00:00
|
|
|
out << statuses[static_cast<uint8_t>(status)];
|
2023-11-21 22:19:08 +00:00
|
|
|
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;
|
2023-12-13 20:33:11 +00:00
|
|
|
|
2023-12-22 23:25:20 +00:00
|
|
|
request.responseIsComplete();
|
|
|
|
}
|
|
|
|
|
|
|
|
uint16_t Response::statusCode() const {
|
|
|
|
return statusCodes[static_cast<uint8_t>(status)];
|
2023-11-21 22:19:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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();
|
|
|
|
}
|