summaryrefslogtreecommitdiff
path: root/include/http_utility.hpp
blob: b20952b438eadb7bbeafc7bc88bd85d6aded205c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#pragma once
#include <boost/algorithm/string.hpp>

#include "crow/http_request.h"

namespace http_helpers
{
inline bool requestPrefersHtml(const crow::Request& req)
{
    std::string_view header = req.getHeaderValue("accept");
    std::vector<std::string> encodings;
    // chrome currently sends 6 accepts headers, firefox sends 4.
    encodings.reserve(6);
    boost::split(encodings, header, boost::is_any_of(", "),
                 boost::token_compress_on);
    for (const std::string& encoding : encodings)
    {
        if (encoding == "text/html")
        {
            return true;
        }
        else if (encoding == "application/json")
        {
            return false;
        }
    }
    return false;
}

inline std::string urlEncode(const std::string_view value)
{
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;

    for (const char c : value)
    {
        // Keep alphanumeric and other accepted characters intact
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
        {
            escaped << c;
            continue;
        }

        // Any other characters are percent-encoded
        escaped << std::uppercase;
        escaped << '%' << std::setw(2)
                << static_cast<int>(static_cast<unsigned char>(c));
        escaped << std::nouppercase;
    }

    return escaped.str();
}
} // namespace http_helpers