Ed Tanous | 9bd21fc | 2018-04-26 16:08:56 -0700 | [diff] [blame] | 1 | #pragma once |
| 2 | #include <boost/algorithm/string.hpp> |
| 3 | |
Ed Tanous | c94ad49 | 2019-10-10 15:39:33 -0700 | [diff] [blame] | 4 | #include "http_request.h" |
Tanous | f00032d | 2018-11-05 01:18:10 -0300 | [diff] [blame] | 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 | 39e7750 | 2019-03-04 17:35:53 -0800 | [diff] [blame] | 10 | std::string_view header = req.getHeaderValue("accept"); |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 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 | else if (encoding == "application/json") |
| 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 | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 54 | } // namespace http_helpers |