blob: 119a1eefb385c7c1cc0e77d03873188374f66449 [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{
8inline bool requestPrefersHtml(const crow::Request& req)
9{
Ed Tanous753d0342021-07-01 07:57:30 -070010 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 Tanous1abe55e2018-09-05 08:30:59 -070017 {
Ed Tanous753d0342021-07-01 07:57:30 -070018 if (encoding == "text/html")
Ed Tanous1abe55e2018-09-05 08:30:59 -070019 {
20 return true;
21 }
Ed Tanous753d0342021-07-01 07:57:30 -070022 if (encoding == "application/json")
Ed Tanous1abe55e2018-09-05 08:30:59 -070023 {
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