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::literals;
63
64 return malloy::split(field_value, "; "sv);
65 }
66
76 template<bool isReq, typename Fields>
77 [[nodiscard]]
78 std::optional<std::string_view>
79 cookie_value(const boost::beast::http::header<isReq, Fields>& header, const std::string_view cookie_name)
80 {
81 const auto& [begin, end] = header.equal_range(field::cookie);
82 for (auto it = begin; it != end; it++) {
83 const auto& str = it->value();
84
85 const auto& sep_pos = it->value().find('=');
86 if (sep_pos == std::string::npos)
87 continue;
88
89 const std::string_view key{ str.substr(0, sep_pos) };
90 const std::string_view value{ str.substr(sep_pos+1) };
91
92 if (key != cookie_name)
93 continue;
94
95 return value;
96 }
97
98 return std::nullopt;
99 }
100
101}
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:79
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:88