blob: ef65e23419c9f7f1dca7b133f652a46d3cb2fe42 [file] [log] [blame]
Ed Tanous9bd21fc2018-04-26 16:08:56 -07001#pragma once
Ed Tanous04e438c2020-10-03 08:06:26 -07002#include "http_request.hpp"
Tanousf00032d2018-11-05 01:18:10 -03003
Gunnar Mills1214b7e2020-06-04 10:11:30 -05004#include <boost/algorithm/string.hpp>
5
Ed Tanous1abe55e2018-09-05 08:30:59 -07006namespace http_helpers
7{
John Edward Broadbent59b98b22021-07-13 15:36:32 -07008inline bool requestPrefersHtml(std::string_view header)
Ed Tanous1abe55e2018-09-05 08:30:59 -07009{
Ed Tanous753d0342021-07-01 07:57:30 -070010 std::vector<std::string> encodings;
11 // chrome currently sends 6 accepts headers, firefox sends 4.
12 encodings.reserve(6);
13 boost::split(encodings, header, boost::is_any_of(", "),
14 boost::token_compress_on);
15 for (const std::string& encoding : encodings)
Ed Tanous1abe55e2018-09-05 08:30:59 -070016 {
Ed Tanous753d0342021-07-01 07:57:30 -070017 if (encoding == "text/html")
Ed Tanous1abe55e2018-09-05 08:30:59 -070018 {
19 return true;
20 }
Ed Tanous753d0342021-07-01 07:57:30 -070021 if (encoding == "application/json")
Ed Tanous1abe55e2018-09-05 08:30:59 -070022 {
23 return false;
24 }
Ed Tanous9bd21fc2018-04-26 16:08:56 -070025 }
Ed Tanous1abe55e2018-09-05 08:30:59 -070026 return false;
Ed Tanous9bd21fc2018-04-26 16:08:56 -070027}
Ed Tanous6b5e77d2018-11-16 14:52:56 -080028
Ed Tanous39e77502019-03-04 17:35:53 -080029inline std::string urlEncode(const std::string_view value)
Ed Tanous6b5e77d2018-11-16 14:52:56 -080030{
31 std::ostringstream escaped;
32 escaped.fill('0');
33 escaped << std::hex;
34
35 for (const char c : value)
36 {
37 // Keep alphanumeric and other accepted characters intact
38 if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
39 {
40 escaped << c;
41 continue;
42 }
43
44 // Any other characters are percent-encoded
45 escaped << std::uppercase;
46 escaped << '%' << std::setw(2)
47 << static_cast<int>(static_cast<unsigned char>(c));
48 escaped << std::nouppercase;
49 }
50
51 return escaped.str();
52}
Ed Tanous23a21a12020-07-25 04:45:05 +000053} // namespace http_helpers