dart-lang / io

Utilities for the Dart VM's dart:io.
https://pub.dev/packages/io
BSD 3-Clause "New" or "Revised" License
49 stars 15 forks source link

Add function to create list of cookies from `set-cookie` header with multiple cookies #98

Open KiraResari opened 1 year ago

KiraResari commented 1 year ago

Situation Some websites and API calls return multiple cookies at once, like this:

Set-Cookie: firstCookie=someCookieValue; Path=/; Secure; HTTPOnly
Set-Cookie: secondCookie=anotherCookieValue; Path=/; Secure; HTTPOnly

In the Dart Response object, they are grouped in a single map entry like this:

response
    headers
        "set-cookie": "firstCookie=someCookieValue; Path=/; Secure; HTTPOnly,secondCookie=anotherCookieValue; Path=/; Secure; HTTPOnly"

The Cookie class has a Cookie.fromSetCookieValue constructor, that will naturally not work with a situation where the set-cookie header entry contains multiple cookies.

Suggestion Add a static method List<Cookie> fromSetCookieValues(String value) to the Cookie that can be given a string containing multiple cookies, like this:

List<Cookie> cookiesInResponse = Cookie.fromSetCookieValues("firstCookie=someCookieValue; Path=/; Secure; HTTPOnly,secondCookie=anotherCookieValue; Path=/; Secure; HTTPOnly");

A practical example would then look like this:

Response responseWithMultipleCookies = await post(...);
List<Cookie> cookiesInResponse = Cookie.fromSetCookieValues(responseWithMultipleCookies.headers["set-cookie"]);

That function could look somewhat like this:

static List<Cookie> fromSetCookieValues(String value){
    List<Cookie> cookies = [];
    List<String> cookieStrings = value.split(",");
        for(var cookieString in cookieStrings){
            cookies.add(Cookie.fromSetCookieValue(cookieString));
        }
    }
    return cookies;
}
houdinihacker commented 1 year ago

This repo does nothing with requests / cookies. Anyway, you can find a plenty of packages that do exactly what you are asking, for example - sweet_cookie_jar