createFileHandler function
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.
Implementation
Handler createFileHandler(String path, {String? url, String? contentType}) {
final file = File(path);
if (!file.existsSync()) {
throw ArgumentError.value(path, 'path', 'does not exist.');
} else if (url != null && !p.url.isRelative(url)) {
throw ArgumentError.value(url, 'url', 'must be relative.');
}
final mimeType = contentType ?? _defaultMimeTypeResolver.lookup(path);
url ??= p.toUri(p.basename(path)).toString();
return (request) {
if (request.url.path != url) return Response.notFound('Not Found');
return _handleFile(request, file, () => mimeType);
};
}