accepts method

bool accepts(
  1. Object? contentType, {
  2. bool strict = false,
})

Returns true if the client's Accept header indicates that the given contentType is considered a valid response.

You cannot provide a null contentType. Without an Accept header, every type is accepted. Otherwise contentType must match one of the header's media ranges: exactly, through a type wildcard (text/* accepts text/html), or through */*. Ranges with q=0 (explicitly unacceptable) never match. To ignore the */* wildcard, pass strict as true.

contentType can be either of the following:

  • A MediaType, whose mimeType is used.
  • Any other Dart value, whose toString() is used (parameters such as ; charset=utf-8 are ignored).

Implementation

bool accepts(Object? contentType, {bool strict = false}) {
  var contentTypeString = contentType is MediaType
      ? contentType.mimeType
      : contentType?.toString();

  // Change to assert
  if (contentTypeString == null) {
    _log.severe('RequestContext.accepts is null');
    throw ArgumentError(
      'RequestContext.accepts expects the `contentType` parameter to NOT be null.',
    );
  }

  var accepted = _acceptedRanges;
  if (accepted == null) return true;

  var wanted = contentTypeString.split(';').first.trim().toLowerCase();
  if (wanted == '*/*') return !strict && accepted.contains('*/*');

  var slash = wanted.indexOf('/');
  var type = slash == -1 ? wanted : wanted.substring(0, slash);

  // A more specific range rejected with q=0 beats a wildcard (RFC 9110).
  var rejected = _rejectedRanges!;
  if (rejected.contains(wanted)) return false;
  if (rejected.contains('$type/*') && !accepted.contains(wanted)) {
    return false;
  }

  for (var range in accepted) {
    if (range == '*/*') {
      if (!strict) return true;
    } else if (range == wanted) {
      return true;
    } else if (range.endsWith('/*') &&
        range.substring(0, range.length - 2) == type) {
      return true;
    }
  }
  return false;
}