cookieHeader static method
Returns the cookie header appropriate for this request
,
taken from the cookies
list.
cookies
can be a List
The returned map is the 'Cookie:' header, with the value=name; value2=name2 as the value.
Implementation
static Map<String, String> cookieHeader(dynamic cookies, String url) {
final Uri uri;
try {
uri = Uri.parse(url);
} catch (e) {
_log.fine('Invalid url: $url error: $e');
return {};
}
final List<Cookie> cookieList = switch (cookies) {
http.Response response =>
cookiesFromSetCookie(response.headers['set-cookie'] ?? ''),
List<Cookie> list => list,
String _ => cookiesFromSetCookie(cookies),
_ => throw ArgumentError(
'cookies parameter must be a http.Response object, a String or a List<Cookie>')
};
final path = uri.path.isNotEmpty ? uri.path : '/';
final validCookies = cookieList.where((cookie) =>
(cookie.maxAge == null || cookie.maxAge! > 0) &&
(cookie.domain == null ||
uri.host.endsWith(cookie.domain!) ||
(cookie.domain!.startsWith('.') &&
uri.host == cookie.domain!.substring(1))) &&
(cookie.path == null || path.startsWith(cookie.path!)) &&
(cookie.expires == null || cookie.expires!.isAfter(DateTime.now())) &&
(!cookie.secure || uri.scheme == 'https'));
final cookieHeaderValue = validCookies
.map((c) => c.name.isNotEmpty ? '${c.name}=${c.value}' : c.value)
.join('; ');
return cookieHeaderValue.isNotEmpty ? {'Cookie': cookieHeaderValue} : {};
}