cookies.hpp
1 #ifndef XXHR_COOKIES_H
2 #define XXHR_COOKIES_H
3 
4 #include <initializer_list>
5 #include <map>
6 #include <sstream>
7 #include <string>
8 #include <regex>
9 #include <utility>
10 #include <functional>
11 
12 #include <boost/algorithm/string/trim_all.hpp>
13 
14 #include "util.hpp"
15 
16 #include <iostream>
17 
18 namespace xxhr {
19 
20 class Cookies {
21  public:
22  Cookies() {}
23  Cookies(const std::initializer_list<std::pair<const std::string, std::string>>& pairs)
24  : map_{pairs} {};
25  Cookies(const std::map<std::string, std::string>& map) : map_{map} {}
26 
27  std::string& operator[](const std::string& key) { return map_[key]; }
28 
29  std::string GetEncoded() const {
30  std::stringstream stream;
31  for (const auto& item : map_) {
32  stream << xxhr::util::urlEncode(item.first) << "=";
33  // special case version 1 cookies, which can be distinguished by
34  // beginning and trailing quotes
35  if (!item.second.empty() && item.second.front() == '"' && item.second.back() == '"') {
36  stream << item.second;
37  } else {
38  stream << xxhr::util::urlEncode(item.second);
39  }
40  stream << "; ";
41  }
42  return stream.str();
43  }
44 
45  inline void parse_cookie_string(const std::string& cookie_str) {
46  using namespace boost::algorithm;
47 
48  std::regex cookies_rx(";");
49  std::vector<std::string> cookies(
50  std::sregex_token_iterator(
51  cookie_str.begin(), cookie_str.end(), cookies_rx, -1),
52  std::sregex_token_iterator()
53  );
54 
55  for (auto& cookie : cookies) {
56  std::regex rx_cookie("([^=]+)=([^;]+)");
57  std::smatch match;
58  std::regex_match(cookie, match, rx_cookie);
59  map_.insert(std::make_pair(trim_all_copy(match[1].str()), match[2].str()));
60  }
61  }
62 
63  private:
64  std::map<std::string, std::string> map_;
65 
66  public:
67  decltype(map_) all() const { return map_; }
68 };
69 
70 
71 } // namespace xxhr
72 
73 #endif
main library namespace
Definition: api.hpp:19