parseRetryAfter function

Duration? parseRetryAfter(
  1. String? value, {
  2. DateTime? now,
})

The wait a Retry-After header asks for (whole seconds or an HTTP date); null when absent, invalid or negative.

Implementation

Duration? parseRetryAfter(String? value, {DateTime? now}) {
  if (value == null) return null;
  final text = value.trim();
  if (text.isEmpty) return null;
  if (RegExp(r'^-?\d+$').hasMatch(text)) {
    final seconds = int.tryParse(text);
    return seconds == null || seconds < 0 ? null : Duration(seconds: seconds);
  }
  final DateTime moment;
  try {
    moment = HttpDate.parse(text);
  } on HttpException {
    return null;
  } on FormatException {
    return null;
  } on RangeError {
    return null;
  }
  final wait = moment.difference(now ?? DateTime.now());
  return wait.isNegative ? null : wait;
}