1 #pragma once 2 #include "http_request.hpp" 3 4 #include <boost/algorithm/string.hpp> 5 6 namespace http_helpers 7 { 8 inline bool requestPrefersHtml(const crow::Request& req) 9 { 10 std::string_view header = req.getHeaderValue("accept"); 11 std::vector<std::string> encodings; 12 // chrome currently sends 6 accepts headers, firefox sends 4. 13 encodings.reserve(6); 14 boost::split(encodings, header, boost::is_any_of(", "), 15 boost::token_compress_on); 16 for (const std::string& encoding : encodings) 17 { 18 if (encoding == "text/html") 19 { 20 return true; 21 } 22 if (encoding == "application/json") 23 { 24 return false; 25 } 26 } 27 return false; 28 } 29 30 inline std::string urlEncode(const std::string_view value) 31 { 32 std::ostringstream escaped; 33 escaped.fill('0'); 34 escaped << std::hex; 35 36 for (const char c : value) 37 { 38 // Keep alphanumeric and other accepted characters intact 39 if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') 40 { 41 escaped << c; 42 continue; 43 } 44 45 // Any other characters are percent-encoded 46 escaped << std::uppercase; 47 escaped << '%' << std::setw(2) 48 << static_cast<int>(static_cast<unsigned char>(c)); 49 escaped << std::nouppercase; 50 } 51 52 return escaped.str(); 53 } 54 } // namespace http_helpers 55