From 72fbf82cd8ca1794fde0b1348956892fd87f2f12 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Wed, 13 May 2020 11:40:42 +0200 Subject: Use map --- response.cpp | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/response.cpp b/response.cpp index 706090e..a5fb8c3 100644 --- a/response.cpp +++ b/response.cpp @@ -183,27 +183,25 @@ std::string GetRequestParam(const std::string& key, RequestContext& req_ctx) throw std::runtime_error("Unsupported request param: "s + key); } +std::unordered_map> SetResponseHeaderActions{ + { "cache_control", [](const std::string& value, response_type& res){res.set(http::field::cache_control, value);} }, + { "content_disposition", [](const std::string& value, response_type& res){res.set(http::field::content_disposition, value);} },// e.g. attachment; ... + { "content_type", [](const std::string& value, response_type& res){res.set(http::field::content_type, value);} },// e.g. text/html + { "location", [](const std::string& value, response_type& res){res.set(http::field::location, value);} },// e.g. 301 Moved Permanently: new Location + { "server", [](const std::string& value, response_type& res){res.set(http::field::server, value);} }, // Server name/version string + { "set_cookie", [](const std::string& value, response_type& res){res.set(http::field::set_cookie, value);} }, + { "status", [](const std::string& value, response_type& res){res.result(unsigned(stoul(value)));} }, // HTTP Status, e.g. "200" (OK) +}; + void SetResponseHeader(const std::string& key, const std::string& value, response_type& res) { // following are the supported fields: - // TODO: unordered_map - if (key == "status") { // HTTP Status, e.g. "200" (OK) - res.result(unsigned(stoul(value))); - } else if (key == "server") { // Server name/version string - res.set(http::field::server, value); - } else if (key == "content_type") { // e.g. text/html - res.set(http::field::content_type, value); - } else if (key == "content_disposition") { // e.g. attachment; ... - res.set(http::field::content_disposition, value); - } else if (key == "location") { // e.g. 301 Moved Permanently: new Location - res.set(http::field::location, value); - } else if (key == "cache_control") { - res.set(http::field::cache_control, value); - } else if (key == "set_cookie") { - res.set(http::field::set_cookie, value); - } else + auto it{SetResponseHeaderActions.find(key)}; + if (it == SetResponseHeaderActions.end()) throw std::runtime_error("Unsupported response field: "s + key); + + it->second(value, res); } response_type HttpStatus(std::string status, std::string message, response_type& res) -- cgit v1.2.3