parseLinkHeader function
Parses an HTTP Link header value into a list of LinkEntry.
Handles:
- Multiple links separated by
, - Attributes separated by
; - Quoted and unquoted attribute values
- Multiple
Linkheader values joined with,
Example input:
<https://hub.example.com>; rel="mercure", <https://example.com/foo>; rel="self"
Implementation
List<LinkEntry> parseLinkHeader(String header) {
final entries = <LinkEntry>[];
// Split on commas that are NOT inside angle brackets
final linkStrings = _splitLinks(header);
for (final linkStr in linkStrings) {
final trimmed = linkStr.trim();
if (trimmed.isEmpty) continue;
// Extract URL from angle brackets
final urlMatch = RegExp(r'<([^>]*)>').firstMatch(trimmed);
if (urlMatch == null) continue;
final url = urlMatch.group(1)!;
final rest = trimmed.substring(urlMatch.end);
// Parse attributes
final attributes = <String, String>{};
final attrPattern =
RegExp(r';\s*(\w[\w.-]*)(?:\s*=\s*(?:"([^"]*)"|([^\s;,]*)))?');
for (final match in attrPattern.allMatches(rest)) {
final key = match.group(1)!.toLowerCase();
final value = match.group(2) ?? match.group(3) ?? '';
attributes[key] = value;
}
entries.add(LinkEntry(
url: url,
rel: attributes['rel'],
attributes: attributes,
));
}
return entries;
}