blob: e0166e338be9c01e825173f4691394d86a770390 [file] [log] [blame]
Ed Tanous9bd21fc2018-04-26 16:08:56 -07001#pragma once
Ed Tanousc94ad492019-10-10 15:39:33 -07002#include "http_request.h"
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{
8inline bool requestPrefersHtml(const crow::Request& req)
9{
Ed Tanous39e77502019-03-04 17:35:53 -080010 std::string_view header = req.getHeaderValue("accept");
Ed Tanous1abe55e2018-09-05 08:30:59 -070011 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 Tanous9bd21fc2018-04-26 16:08:56 -070026 }
Ed Tanous1abe55e2018-09-05 08:30:59 -070027 return false;
Ed Tanous9bd21fc2018-04-26 16:08:56 -070028}
Ed Tanous6b5e77d2018-11-16 14:52:56 -080029
Ed Tanous39e77502019-03-04 17:35:53 -080030inline std::string urlEncode(const std::string_view value)
Ed Tanous6b5e77d2018-11-16 14:52:56 -080031{
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 Tanous23a21a12020-07-25 04:45:05 +000054} // namespace http_helpers