1 // SPDX-License-Identifier: Apache-2.0 2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors 3 #pragma once 4 5 #include "authentication.hpp" 6 #include "boost_formatters.hpp" 7 #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> 16 #include <nlohmann/json.hpp> 17 18 #include <array> 19 20 namespace crow 21 { 22 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