Oat++ Get Cookie for request

130 Views Asked by At

I am working on an Oat++ project that will serve web pages, part of this will require cookies. In Oat++ how do you get the key/value pair for a cookie please?

In quart for Python I would use:

retrieved_token = request.cookies.get(self.COOKIE_TOKEN)
retrieved_username = request.cookies.get(self.COOKIE_USER)

What is the equivalent in Oat++ for C++ please?

Research

Setting a cookie in Oat++ is part of the header (see GitHub link here

1

There are 1 best solutions below

1
alexwbt On BEST ANSWER

In Oat++, there is no built-in getCookie method. You must manually parse it from the cookie header.

The util functions for parsing cookies:

inline void ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
        return !std::isspace(ch);
    }));
}

std::vector<std::string> parseCookieHeader(const std::string &cookieHeader)
{
  std::vector<std::string> cookieValues;
  std::istringstream iss(cookieHeader);
  std::string cookieValue;
  while (std::getline(iss, cookieValue, ';'))
  {
    ltrim(cookieValue);
    cookieValues.push_back(cookieValue);
  }
  return cookieValues;
}

bool parseCookieValue(const std::string &cookieValue, std::string &name, std::string &value)
{
  size_t delimiterPos = cookieValue.find('=');
  if (delimiterPos != std::string::npos)
  {
    name = cookieValue.substr(0, delimiterPos);
    value = cookieValue.substr(delimiterPos + 1);
    return true;
  }
  return false;
}

In the controller:

// get cookie header from request
auto cookieHeader = request->getHeader("Cookie")->getValue();
std::vector<std::string> cookieValues = parseCookieHeader(cookieHeader);

for (const auto& cookieValue : cookieValues) {
  std::string name, value;
  if (parseCookieValue(cookieValue, name, value)) {
    std::cout << "Name: " << name << ", Value: " << value << std::endl;
  }
}