Парсинг куков для веб-сервера

Ответить
ya
^-^
Сообщения: 2336
Зарегистрирован: 16 дек 2021, 19:56

Парсинг куков для веб-сервера

Сообщение ya »

Код: Выделить всё

#include <iostream>
#include <string>
#include <map>
#include <sstream>

std::map<std::string, std::string> parseCookies(const std::string& cookieString) {
    std::map<std::string, std::string> cookies;
    std::istringstream stream0(cookieString);
    std::string cookie;

    // Пропускаем часть "Cookie: "
    if (std::getline(stream0, cookie, ':')) {
        // Пропускаем пробелы
        std::getline(stream0 >> std::ws, cookie, ' ');
    }

    std::istringstream stream(cookieString);
    // Разделяем куки по символу ";" и парсим каждую пару
    while (std::getline(stream, cookie, ';')) {
        // Удаляем возможные пробелы слева и справа
        cookie.erase(0, cookie.find_first_not_of(" \t"));
        cookie.erase(cookie.find_last_not_of(" \t") + 1);

        // Ищем знак "=" чтобы разделить ключ и значение
        std::size_t pos = cookie.find('=');
        if (pos != std::string::npos) {
            std::string key = cookie.substr(0, pos);
            std::string value = cookie.substr(pos + 1);
            cookies[key] = value;
        }
    }

    return cookies;
}

int main() {
    std::string cookieString = "Cookie: cockpit=dj0yO2s9MzRkNjQ3ZWJkZGI5ZjQzODNhNjkzYTg0YTBlYWQwYTg5NGRhMWU4ODczMTQ5NmUwZTZkMTljZDFjNmJmOTQ5NA==; user_id=3; user_id168317295=3";

    std::map<std::string, std::string> cookies = parseCookies(cookieString);

    // Вывод парсенных куки
    for (const auto& pair : cookies) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}
Ответить