140e9b92eSEd Tanous // SPDX-License-Identifier: Apache-2.0
240e9b92eSEd Tanous // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3ed5f8954SEd Tanous #pragma once
4ed5f8954SEd Tanous
595c6307aSEd Tanous #include "boost_formatters.hpp"
6ed5f8954SEd Tanous #include "http_response.hpp"
7ed5f8954SEd Tanous #include "http_utility.hpp"
8ed5f8954SEd Tanous #include "json_html_serializer.hpp"
9ed5f8954SEd Tanous #include "logging.hpp"
10ed5f8954SEd Tanous #include "security_headers.hpp"
11ed5f8954SEd Tanous
12*d7857201SEd Tanous #include <boost/beast/http/field.hpp>
13ed5f8954SEd Tanous #include <nlohmann/json.hpp>
14ed5f8954SEd Tanous
15ed5f8954SEd Tanous #include <array>
16*d7857201SEd Tanous #include <string>
17*d7857201SEd Tanous #include <string_view>
18*d7857201SEd Tanous #include <utility>
19ed5f8954SEd Tanous
20ed5f8954SEd Tanous namespace crow
21ed5f8954SEd Tanous {
22ed5f8954SEd Tanous
completeResponseFields(std::string_view accepts,Response & res)2389cda63dSEd Tanous inline void completeResponseFields(std::string_view accepts, Response& res)
24ed5f8954SEd Tanous {
2589cda63dSEd Tanous BMCWEB_LOG_INFO("Response: {}", res.resultInt());
2689cda63dSEd Tanous addSecurityHeaders(res);
27ed5f8954SEd Tanous
28ed5f8954SEd Tanous res.setHashAndHandleNotModified();
2927b0cf90SEd Tanous if (res.jsonValue.is_structured())
30ed5f8954SEd Tanous {
31ed5f8954SEd Tanous using http_helpers::ContentType;
32ed5f8954SEd Tanous std::array<ContentType, 3> allowed{ContentType::CBOR, ContentType::JSON,
33ed5f8954SEd Tanous ContentType::HTML};
3489cda63dSEd Tanous ContentType preferred = getPreferredContentType(accepts, allowed);
35ed5f8954SEd Tanous
368ece0e45SEd Tanous if (preferred == ContentType::HTML)
37ed5f8954SEd Tanous {
38ed5f8954SEd Tanous json_html_util::prettyPrintJson(res);
39ed5f8954SEd Tanous }
408ece0e45SEd Tanous else if (preferred == ContentType::CBOR)
41ed5f8954SEd Tanous {
42ed5f8954SEd Tanous res.addHeader(boost::beast::http::field::content_type,
43ed5f8954SEd Tanous "application/cbor");
4427b0cf90SEd Tanous std::string cbor;
4527b0cf90SEd Tanous nlohmann::json::to_cbor(res.jsonValue, cbor);
4627b0cf90SEd Tanous res.write(std::move(cbor));
47ed5f8954SEd Tanous }
48ed5f8954SEd Tanous else
49ed5f8954SEd Tanous {
508ece0e45SEd Tanous // Technically preferred could also be NoMatch here, but we'd
51ed5f8954SEd Tanous // like to default to something rather than return 400 for
52ed5f8954SEd Tanous // backward compatibility.
53ed5f8954SEd Tanous res.addHeader(boost::beast::http::field::content_type,
54ed5f8954SEd Tanous "application/json");
5527b0cf90SEd Tanous res.write(res.jsonValue.dump(
5627b0cf90SEd Tanous 2, ' ', true, nlohmann::json::error_handler_t::replace));
57ed5f8954SEd Tanous }
58ed5f8954SEd Tanous }
59ed5f8954SEd Tanous }
60ed5f8954SEd Tanous } // namespace crow
61