Ed Tanous | 9bd21fc | 2018-04-26 16:08:56 -0700 | [diff] [blame] | 1 | #pragma once |
Ed Tanous | 04e438c | 2020-10-03 08:06:26 -0700 | [diff] [blame] | 2 | #include "http_request.hpp" |
Tanous | f00032d | 2018-11-05 01:18:10 -0300 | [diff] [blame] | 3 | |
Gunnar Mills | 1214b7e | 2020-06-04 10:11:30 -0500 | [diff] [blame] | 4 | #include <boost/algorithm/string.hpp> |
| 5 | |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 6 | namespace http_helpers |
| 7 | { |
| 8 | inline bool requestPrefersHtml(const crow::Request& req) |
| 9 | { |
Ed Tanous | 753d034 | 2021-07-01 07:57:30 -0700 | [diff] [blame] | 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) |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 17 | { |
Ed Tanous | 753d034 | 2021-07-01 07:57:30 -0700 | [diff] [blame] | 18 | if (encoding == "text/html") |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 19 | { |
| 20 | return true; |
| 21 | } |
Ed Tanous | 753d034 | 2021-07-01 07:57:30 -0700 | [diff] [blame] | 22 | if (encoding == "application/json") |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 23 | { |
| 24 | return false; |
| 25 | } |
Ed Tanous | 9bd21fc | 2018-04-26 16:08:56 -0700 | [diff] [blame] | 26 | } |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 27 | return false; |
Ed Tanous | 9bd21fc | 2018-04-26 16:08:56 -0700 | [diff] [blame] | 28 | } |
Ed Tanous | 6b5e77d | 2018-11-16 14:52:56 -0800 | [diff] [blame] | 29 | |
Ed Tanous | 39e7750 | 2019-03-04 17:35:53 -0800 | [diff] [blame] | 30 | inline std::string urlEncode(const std::string_view value) |
Ed Tanous | 6b5e77d | 2018-11-16 14:52:56 -0800 | [diff] [blame] | 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 | } |
Ed Tanous | 23a21a1 | 2020-07-25 04:45:05 +0000 | [diff] [blame] | 54 | } // namespace http_helpers |