blob: 46e0c66514c0a0febc7f40f7616a28cd885b5dc0 [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
Ed Tanoused5f8952023-06-22 14:06:22 -07003#pragma once
4
5#include "authentication.hpp"
Ed Tanous95c63072024-03-26 13:19:52 -07006#include "boost_formatters.hpp"
Ed Tanoused5f8952023-06-22 14:06:22 -07007#include "http_request.hpp"
8#include "http_response.hpp"
9#include "http_utility.hpp"
10#include "json_html_serializer.hpp"
11#include "logging.hpp"
12#include "security_headers.hpp"
13#include "utils/hex_utils.hpp"
14
15#include <boost/beast/http/message.hpp>
Ed Tanoused5f8952023-06-22 14:06:22 -070016#include <nlohmann/json.hpp>
17
18#include <array>
19
20namespace crow
21{
22
Ed Tanous89cda632024-04-16 08:45:54 -070023inline void completeResponseFields(std::string_view accepts, Response& res)
Ed Tanoused5f8952023-06-22 14:06:22 -070024{
Ed Tanous89cda632024-04-16 08:45:54 -070025 BMCWEB_LOG_INFO("Response: {}", res.resultInt());
26 addSecurityHeaders(res);
Ed Tanoused5f8952023-06-22 14:06:22 -070027
28 res.setHashAndHandleNotModified();
Ed Tanous27b0cf92023-08-07 12:02:40 -070029 if (res.jsonValue.is_structured())
Ed Tanoused5f8952023-06-22 14:06:22 -070030 {
31 using http_helpers::ContentType;
32 std::array<ContentType, 3> allowed{ContentType::CBOR, ContentType::JSON,
33 ContentType::HTML};
Ed Tanous89cda632024-04-16 08:45:54 -070034 ContentType preferred = getPreferredContentType(accepts, allowed);
Ed Tanoused5f8952023-06-22 14:06:22 -070035
Ed Tanous8ece0e42024-01-02 13:16:50 -080036 if (preferred == ContentType::HTML)
Ed Tanoused5f8952023-06-22 14:06:22 -070037 {
38 json_html_util::prettyPrintJson(res);
39 }
Ed Tanous8ece0e42024-01-02 13:16:50 -080040 else if (preferred == ContentType::CBOR)
Ed Tanoused5f8952023-06-22 14:06:22 -070041 {
42 res.addHeader(boost::beast::http::field::content_type,
43 "application/cbor");
Ed Tanous27b0cf92023-08-07 12:02:40 -070044 std::string cbor;
45 nlohmann::json::to_cbor(res.jsonValue, cbor);
46 res.write(std::move(cbor));
Ed Tanoused5f8952023-06-22 14:06:22 -070047 }
48 else
49 {
Ed Tanous8ece0e42024-01-02 13:16:50 -080050 // Technically preferred could also be NoMatch here, but we'd
Ed Tanoused5f8952023-06-22 14:06:22 -070051 // like to default to something rather than return 400 for
52 // backward compatibility.
53 res.addHeader(boost::beast::http::field::content_type,
54 "application/json");
Ed Tanous27b0cf92023-08-07 12:02:40 -070055 res.write(res.jsonValue.dump(
56 2, ' ', true, nlohmann::json::error_handler_t::replace));
Ed Tanoused5f8952023-06-22 14:06:22 -070057 }
58 }
59}
60} // namespace crow