Malloy
Loading...
Searching...
No Matches
utils.hpp
1#pragma once
2
3#include "types.hpp"
4#include "../utils.hpp"
5
6#include <boost/beast/core/string.hpp>
7#include <boost/beast/http/message.hpp>
8
9#include <optional>
10
11namespace malloy::http
12{
13
14 template<bool isReq, typename Fields>
15 [[nodiscard]]
16 std::string_view
17 resource_string(const boost::beast::http::header<isReq, Fields>& header)
18 {
19 const auto target = header.target();
20
21 const auto pos = target.find_first_of("?#");
22 if (pos == std::string::npos)
23 return target;
24 else
25 return target.substr(0, pos);
26 }
27
28 template<bool isReq, typename Fields>
29 void
30 chop_resource(boost::beast::http::header<isReq, Fields>& head, std::string_view resource)
31 {
32 head.target(head.target().substr(resource.size()));
33 }
34
35 template<bool isReq, typename Fields>
36 [[nodiscard]]
37 bool
38 has_field(const boost::beast::http::header<isReq, Fields>& head, const malloy::http::field check)
39 {
40 return head.find(check) != head.end();
41 }
42
57 [[nodiscard]]
58 inline
59 std::vector<std::string_view>
60 split_header_value(std::string_view field_value)
61 {
62 using namespace std::string_view_literals;
63
64 return malloy::split(field_value, "; "sv);
65 }
66
76 // ToDo: This implementation could use some love. It's comparably inefficient as we're splitting first on each
77 // cookie value separation ("; ") and then on each value-pair separator ("="). A more elegant implementation
78 // would just continuously advance through the string.
79 template<bool isReq, typename Fields>
80 [[nodiscard]]
81 std::optional<std::string_view>
82 cookie_value(const boost::beast::http::header<isReq, Fields>& header, const std::string_view cookie_name)
83 {
84 using namespace std::string_view_literals;
85
86 // Get cookie field
87 const auto& it = header.find(field::cookie);
88 if (it == header.cend())
89 return std::nullopt;
90
91 // Split pairs
92 const auto& pairs = split_header_value(it->value());
93
94 // Check each pair
95 for (const std::string_view& pair : pairs) {
96 // Split
97 const auto& parts = malloy::split(pair, "="sv);
98 if (parts.size() != 2)
99 continue;
100
101 // Check cookie name
102 if (parts[0] == cookie_name)
103 return parts[1];
104 }
105
106 return std::nullopt;
107 }
108
109}
Definition: cookie.hpp:8
std::optional< std::string_view > cookie_value(const boost::beast::http::header< isReq, Fields > &header, const std::string_view cookie_name)
Definition: utils.hpp:82
boost::beast::http::field field
Definition: types.hpp:28
std::vector< std::string_view > split_header_value(std::string_view field_value)
Definition: utils.hpp:60
std::vector< std::string_view > split(std::string_view str, std::string_view delimiter)
Definition: utils.hpp:86