parseCacheControl function

Map<String, String?> parseCacheControl(
  1. String header
)

Parses a Cache-Control header into a directive map.

Each comma-separated directive is lower-cased. A key=value directive maps to its value (surrounding double quotes stripped); a bare flag directive such as no-cache maps to null. Empty directives are skipped.

Example:

parseCacheControl('no-cache, max-age=600');
// {'no-cache': null, 'max-age': '600'}

Audited: 2026-06-12 11:26 EDT

Implementation

Map<String, String?> parseCacheControl(String header) {
  final Map<String, String?> directives = <String, String?>{};
  // Split on commas; a directive is either a bare flag or a key=value pair.
  for (final String raw in header.split(',')) {
    final String token = raw.trim();
    if (token.isEmpty) {
      continue;
    }
    final int eq = token.indexOf('=');
    // No '=' means a bare flag directive (e.g. no-cache) with a null value.
    if (eq < 0) {
      directives[token.toLowerCase()] = null;
      continue;
    }
    // eq is an in-range index from indexOf, so both substrings below are bounded.
    // ignore: avoid_string_substring -- eq provably within length (indexOf + guard)
    final String key = token.substring(0, eq).trim().toLowerCase();
    // ignore: avoid_string_substring -- eq + 1 <= length (eq is a valid index)
    final String value = token.substring(eq + 1).trim();
    directives[key] = _unquote(value);
  }
  return directives;
}