blob: a5b3eec3d0fe5e46f86fdb54b19740a2b3943149 [file] [log] [blame]
Ed Tanoused5f8952023-06-22 14:06:22 -07001#pragma once
2
3#include "authentication.hpp"
4#include "http_request.hpp"
5#include "http_response.hpp"
6#include "http_utility.hpp"
7#include "json_html_serializer.hpp"
8#include "logging.hpp"
9#include "security_headers.hpp"
10#include "utils/hex_utils.hpp"
11
12#include <boost/beast/http/message.hpp>
13#include <boost/beast/http/string_body.hpp>
14#include <nlohmann/json.hpp>
15
16#include <array>
17
18namespace crow
19{
20
21inline void completeResponseFields(const Request& req, Response& res)
22{
Ed Tanous62598e32023-07-17 17:06:25 -070023 BMCWEB_LOG_INFO("Response: {} {}", req.url().encoded_path(),
24 res.resultInt());
Ed Tanoused5f8952023-06-22 14:06:22 -070025 addSecurityHeaders(req, res);
26
27 authentication::cleanupTempSession(req);
28
29 res.setHashAndHandleNotModified();
Ed Tanous27b0cf92023-08-07 12:02:40 -070030 if (res.jsonValue.is_structured())
Ed Tanoused5f8952023-06-22 14:06:22 -070031 {
32 using http_helpers::ContentType;
33 std::array<ContentType, 3> allowed{ContentType::CBOR, ContentType::JSON,
34 ContentType::HTML};
35 ContentType prefered =
36 getPreferedContentType(req.getHeaderValue("Accept"), allowed);
37
38 if (prefered == ContentType::HTML)
39 {
40 json_html_util::prettyPrintJson(res);
41 }
42 else if (prefered == ContentType::CBOR)
43 {
44 res.addHeader(boost::beast::http::field::content_type,
45 "application/cbor");
Ed Tanous27b0cf92023-08-07 12:02:40 -070046 std::string cbor;
47 nlohmann::json::to_cbor(res.jsonValue, cbor);
48 res.write(std::move(cbor));
Ed Tanoused5f8952023-06-22 14:06:22 -070049 }
50 else
51 {
52 // Technically prefered could also be NoMatch here, but we'd
53 // like to default to something rather than return 400 for
54 // backward compatibility.
55 res.addHeader(boost::beast::http::field::content_type,
56 "application/json");
Ed Tanous27b0cf92023-08-07 12:02:40 -070057 res.write(res.jsonValue.dump(
58 2, ' ', true, nlohmann::json::error_handler_t::replace));
Ed Tanoused5f8952023-06-22 14:06:22 -070059 }
60 }
61}
62} // namespace crow