blob: 397099297454273c8df2e8a0419a7c8a6337b2e2 [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{
George Liu647b3cd2021-07-05 12:43:56 +08008inline std::vector<std::string> parseAccept(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);
George Liu647b3cd2021-07-05 12:43:56 +080015
16 return encodings;
17}
18
19inline bool requestPrefersHtml(std::string_view header)
20{
21 for (const std::string& encoding : parseAccept(header))
Ed Tanous1abe55e2018-09-05 08:30:59 -070022 {
Ed Tanous753d0342021-07-01 07:57:30 -070023 if (encoding == "text/html")
Ed Tanous1abe55e2018-09-05 08:30:59 -070024 {
25 return true;
26 }
Ed Tanous753d0342021-07-01 07:57:30 -070027 if (encoding == "application/json")
Ed Tanous1abe55e2018-09-05 08:30:59 -070028 {
29 return false;
30 }
Ed Tanous9bd21fc2018-04-26 16:08:56 -070031 }
Ed Tanous1abe55e2018-09-05 08:30:59 -070032 return false;
Ed Tanous9bd21fc2018-04-26 16:08:56 -070033}
Ed Tanous6b5e77d2018-11-16 14:52:56 -080034
George Liu647b3cd2021-07-05 12:43:56 +080035inline bool isOctetAccepted(std::string_view header)
36{
37 for (const std::string& encoding : parseAccept(header))
38 {
39 if (encoding == "*/*" || encoding == "application/octet-stream")
40 {
41 return true;
42 }
43 }
44 return false;
45}
46
Ed Tanous39e77502019-03-04 17:35:53 -080047inline std::string urlEncode(const std::string_view value)
Ed Tanous6b5e77d2018-11-16 14:52:56 -080048{
49 std::ostringstream escaped;
50 escaped.fill('0');
51 escaped << std::hex;
52
53 for (const char c : value)
54 {
55 // Keep alphanumeric and other accepted characters intact
Ed Tanouse662eae2022-01-25 10:39:19 -080056 if ((isalnum(c) != 0) || c == '-' || c == '_' || c == '.' || c == '~')
Ed Tanous6b5e77d2018-11-16 14:52:56 -080057 {
58 escaped << c;
59 continue;
60 }
61
62 // Any other characters are percent-encoded
63 escaped << std::uppercase;
64 escaped << '%' << std::setw(2)
65 << static_cast<int>(static_cast<unsigned char>(c));
66 escaped << std::nouppercase;
67 }
68
69 return escaped.str();
70}
Ed Tanous23a21a12020-07-25 04:45:05 +000071} // namespace http_helpers