1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4
5 #include "boost_formatters.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
12 #include <boost/beast/http/field.hpp>
13 #include <nlohmann/json.hpp>
14
15 #include <array>
16 #include <string>
17 #include <string_view>
18 #include <utility>
19
20 namespace crow
21 {
22
completeResponseFields(std::string_view accepts,Response & res)23 inline void completeResponseFields(std::string_view accepts, Response& res)
24 {
25 BMCWEB_LOG_INFO("Response: {}", res.resultInt());
26 addSecurityHeaders(res);
27
28 res.setHashAndHandleNotModified();
29 if (res.jsonValue.is_structured())
30 {
31 using http_helpers::ContentType;
32 std::array<ContentType, 3> allowed{ContentType::CBOR, ContentType::JSON,
33 ContentType::HTML};
34 ContentType preferred = getPreferredContentType(accepts, allowed);
35
36 if (preferred == ContentType::HTML)
37 {
38 json_html_util::prettyPrintJson(res);
39 }
40 else if (preferred == ContentType::CBOR)
41 {
42 res.addHeader(boost::beast::http::field::content_type,
43 "application/cbor");
44 std::string cbor;
45 nlohmann::json::to_cbor(res.jsonValue, cbor);
46 res.write(std::move(cbor));
47 }
48 else
49 {
50 // Technically preferred could also be NoMatch here, but we'd
51 // 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");
55 res.write(res.jsonValue.dump(
56 2, ' ', true, nlohmann::json::error_handler_t::replace));
57 }
58 }
59 }
60 } // namespace crow
61