loadAsset function

Future loadAsset(
  1. HttpConnect connect,
  2. Asset asset, [
  3. AssetCache? cache
])

Loads an asset into the given response.

To load a file, you can do:

loadAsset(connect, FileAsset(file));

It throws Http404 if Asset.lastModified throws an exception.

Implementation

Future loadAsset(HttpConnect connect, Asset asset, [AssetCache? cache]) async {
  final response = connect.response,
    isIncluded = connect.isIncluded;
  ContentType? contentType;
  if (!isIncluded) {
    contentType = getContentType(asset.path, isExtension: false);
    if (contentType != null)
      response.headers.contentType = contentType;
  }

  DateTime lastModified;
  try {
    lastModified = await asset.lastModified();
  } catch (_) {
    throw Http404.fromConnect(connect);
  }

  List<int>? content;
  int? assetSize;
  if (cache != null) {
    content = cache.getContent(asset, lastModified);
    if (content != null)
      assetSize = content.length;
  }
  if (assetSize == null)
    assetSize = await asset.length();

  List<_Range>? ranges;
  if (!isIncluded) {
    final detail = _AssetDetail(asset, lastModified, assetSize, cache);
    if (!checkIfHeaders(connect, lastModified, detail.etag))
      return null;

    ranges = _parseRange(connect, detail);
    if (!_setHeaders(connect, detail, ranges))
      return null; //done
  }

  if (content == null && cache != null && cache.shallCache(asset, assetSize)) {
    content = await asset.readAsBytes();
    cache.setContent(asset, lastModified, content);
  }

  if (content != null)
    return _outContentInRanges(response, ranges, contentType, content);
  return _outAssetInRanges(response, ranges, contentType, asset, assetSize);
}