blob: b20952b438eadb7bbeafc7bc88bd85d6aded205c [file] [log] [blame]
Ed Tanous9bd21fc2018-04-26 16:08:56 -07001#pragma once
2#include <boost/algorithm/string.hpp>
3
Tanousf00032d2018-11-05 01:18:10 -03004#include "crow/http_request.h"
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 Tanous1abe55e2018-09-05 08:30:59 -070054} // namespace http_helpers