blob: a5468a405c5fd27bfb68d775e6fcba2f69f9426a [file] [log] [blame]
Ed Tanoused5f8952023-06-22 14:06:22 -07001#pragma once
2
3#include "authentication.hpp"
Ed Tanous95c63072024-03-26 13:19:52 -07004#include "boost_formatters.hpp"
Ed Tanoused5f8952023-06-22 14:06:22 -07005#include "http_request.hpp"
6#include "http_response.hpp"
7#include "http_utility.hpp"
8#include "json_html_serializer.hpp"
9#include "logging.hpp"
10#include "security_headers.hpp"
11#include "utils/hex_utils.hpp"
12
13#include <boost/beast/http/message.hpp>
Ed Tanoused5f8952023-06-22 14:06:22 -070014#include <nlohmann/json.hpp>
15
16#include <array>
17
18namespace crow
19{
20
Ed Tanous89cda632024-04-16 08:45:54 -070021inline void completeResponseFields(std::string_view accepts, Response& res)
Ed Tanoused5f8952023-06-22 14:06:22 -070022{
Ed Tanous89cda632024-04-16 08:45:54 -070023 BMCWEB_LOG_INFO("Response: {}", res.resultInt());
24 addSecurityHeaders(res);
Ed Tanoused5f8952023-06-22 14:06:22 -070025
26 res.setHashAndHandleNotModified();
Ed Tanous27b0cf92023-08-07 12:02:40 -070027 if (res.jsonValue.is_structured())
Ed Tanoused5f8952023-06-22 14:06:22 -070028 {
29 using http_helpers::ContentType;
30 std::array<ContentType, 3> allowed{ContentType::CBOR, ContentType::JSON,
31 ContentType::HTML};
Ed Tanous89cda632024-04-16 08:45:54 -070032 ContentType preferred = getPreferredContentType(accepts, allowed);
Ed Tanoused5f8952023-06-22 14:06:22 -070033
Ed Tanous8ece0e42024-01-02 13:16:50 -080034 if (preferred == ContentType::HTML)
Ed Tanoused5f8952023-06-22 14:06:22 -070035 {
36 json_html_util::prettyPrintJson(res);
37 }
Ed Tanous8ece0e42024-01-02 13:16:50 -080038 else if (preferred == ContentType::CBOR)
Ed Tanoused5f8952023-06-22 14:06:22 -070039 {
40 res.addHeader(boost::beast::http::field::content_type,
41 "application/cbor");
Ed Tanous27b0cf92023-08-07 12:02:40 -070042 std::string cbor;
43 nlohmann::json::to_cbor(res.jsonValue, cbor);
44 res.write(std::move(cbor));
Ed Tanoused5f8952023-06-22 14:06:22 -070045 }
46 else
47 {
Ed Tanous8ece0e42024-01-02 13:16:50 -080048 // Technically preferred could also be NoMatch here, but we'd
Ed Tanoused5f8952023-06-22 14:06:22 -070049 // like to default to something rather than return 400 for
50 // backward compatibility.
51 res.addHeader(boost::beast::http::field::content_type,
52 "application/json");
Ed Tanous27b0cf92023-08-07 12:02:40 -070053 res.write(res.jsonValue.dump(
54 2, ' ', true, nlohmann::json::error_handler_t::replace));
Ed Tanoused5f8952023-06-22 14:06:22 -070055 }
56 }
57}
58} // namespace crow