createFileHandler function

Handler createFileHandler (
  1. String path,
  2. {String url,
  3. String contentType}

Creates a shelf Handler that serves the file at path.

This returns a 404 response for any requests whose Request.url doesn't match url. The url defaults to the basename of path.

This uses the given contentType for the Content-Type header. It defaults to looking up a content type based on path's file extension, and failing that doesn't sent a contentType header at all.


Handler createFileHandler(String path, {String url, String contentType}) {
  var file = new File(path);
  if (!file.existsSync()) {
    throw new ArgumentError.value(path, 'path', 'does not exist.');
  } else if (url != null && !p.url.isRelative(url)) {
    throw new ArgumentError.value(url, 'url', 'must be relative.');

  contentType ??= _defaultMimeTypeResolver.lookup(path);
  url ??= p.toUri(p.basename(path)).toString();

  return (request) {
    if (request.url.path != url) return new Response.notFound('Not Found');
    return _handleFile(request, file, () => contentType);